I agree with the already mentioned StringBuilder
(from the System.Text namespace) approach, but I would suggest creating a helper method to do the string creations. Such a method is easy to reuse (e.g. when converting several strings collected in a list/array), and can display clearly how each character in the source string is handled. Maintenance / Making changes to the conversion logic at a later time will also be quite easy.
Suggested implementation:
private static string GetSentence(string str)
{
var sb = new StringBuilder();
sb.Append(Char.ToUpper(str[0])); // Handle the first char
foreach (var ch in str[1..]) // Then, handle the remaining chars
{
if (Char.IsUpper(ch))
{
sb.Append(' ');
sb.Append(Char.ToLower(ch));
}
else
{
sb.Append(ch);
}
}
return sb.ToString();
}
It can be used on an array of strings, like this:
var strings = new[] { "firstName", "birthOfDate" };
var sentences = strings
.Select(GetSentence)
.ToArray();
foreach (var sentence in sentences)
{
Console.WriteLine(sentence);
}
which produces:
First name
Birth of date
In the example above, the .Select()
method is found in the System.Linq namespace.
Example fiddle here.