Skip to main content
3 of 6
added 627 characters in body
t3chb0t
  • 44.7k
  • 9
  • 84
  • 191

With regex it's virtually a one-liner:

var words = 
    Regex.Matches("SmallFireBall", @"([A-Z][a-z]+)")
    .Cast<Match>()
    .Select(m => m.Value);

var withSpaces = string.Join(" ", words);
  • Regex.Matches - searches an input string for all occurrences of a regular expression and returns all the matches. MSDN
  • [A-Z][a-z]+ - matches strings that begin with a capital letter and are followed by one or more lowercase letters

Output:

Small Fire Ball


Let's review your code anyway and optimize it a little bit. Even without regex it still can be very short.

  • use a StringBuilder for building string dynamically
  • you can use a foreach loop for strings too

x

public static string SplitOnCapitalLetters(string inputString)
{
    var result = new StringBuilder();
    
    foreach (var ch in inputString)
    {
        if (char.IsUpper(ch))
        {
            if (result.Length > 0)
            {
                result.Append(' ');
            }
            
            result.Append(ch);
        }
        else
        {
            result.Append(ch);
        }
    }
    
    return result.ToString();   
}
t3chb0t
  • 44.7k
  • 9
  • 84
  • 191