BestPractice - Transform first character of a string into lower case
I'd like to have a method that transforms the first character of a string into lower case.
My approaches:
1.
public static string ReplaceFirstCharacterToLowerVariant(string name)
{
return String.Format("{0}{1}", name.First().ToString().ToLowerInvariant(), name.Substring(1));
}
2.
public static IEnumerable<char> FirstLetterToLowerCase(string value)
{
var firstChar = (byte)value.First();
return string.Format("{0}{1}", (char)(firstChar + 32), value.Substring(1));
}
What would be your approach?
Solution 1:
I would use simple concatenation:
Char.ToLowerInvariant(name[0]) + name.Substring(1)
The first solution is not optimized because string.Format
is slow and you don't need it if you have a format that will never change. It also generates an extra string to covert the letter to lowercase, which is not needed.
The approach with "+ 32" is ugly / not maintainable as it requires knowledge of ASCII character value offsets. It will also generate incorrect output with Unicode data and ASCII symbol characters.
Solution 2:
Depending on the situation, a little defensive programming might be desirable:
public static string FirstCharacterToLower(string str)
{
if (String.IsNullOrEmpty(str) || Char.IsLower(str, 0))
return str;
return Char.ToLowerInvariant(str[0]) + str.Substring(1);
}
The if
statement also prevents a new string from being built if it's not going to be changed anyway. You might want to have the method fail on null input instead, and throw an ArgumentNullException
.
As people have mentioned, using String.Format
for this is overkill.
Solution 3:
Just in case it helps anybody who happens to stumble across this answer.
I think this would be best as an extension method, then you can call it with yourString.FirstCharacterToLower();
public static class StringExtensions
{
public static string FirstCharacterToLower(this string str)
{
if (String.IsNullOrEmpty(str) || Char.IsLower(str, 0))
{
return str;
}
return Char.ToLowerInvariant(str[0]) + str.Substring(1);
}
}