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
StringBuilderfor building string dynamically - you can use a
foreachloop 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();
}