BestPractice-将字符串的第一个字符转换为小写 [英] 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.
我的方法:
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));
}
您的处理方式是什么?
推荐答案
我将使用简单的串联:
Char.ToLowerInvariant(name[0]) + name.Substring(1)
第一个解决方案未优化,因为 string.Format
速度很慢,如果格式永远不变,则不需要它。
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.
使用 + 32的方法很丑陋/难以维护,因为它需要了解以下内容: ASCII字符值偏移量。还会生成带有Unicode数据和ASCII符号字符的错误输出。
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.
这篇关于BestPractice-将字符串的第一个字符转换为小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!