我想将我的字符串格式化为大写字符格式(即Capitalize First Char Of Words).
For Example -
If Input is: "NEW YORK CITY"
then the desired output is: "New York City"
Run Code Online (Sandbox Code Playgroud)
*我的字符串最多3个字.
之后,谷歌搜索它我找到了几种方法来实现这种方法,但我无法得到哪种方法最好.
方法1:
string City = "NEW YORK CITY";
City = City.ToLower();
string Capatilize_City = "";
Capatilize_City = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(City);
Run Code Online (Sandbox Code Playgroud)
方法2:
string City = "NEW YORK CITY";
string[] lstWord = City.ToLower().Split(' ');
string Capatilize_City = "";
foreach (string s in lstWord)
{
string z = s.Substring(0, 1).ToUpper() + s.Substring(1, s.Length - 1);
Capatilize_City += " " + z;
}
Capatilize_City = Capatilize_City.Trim();
Run Code Online (Sandbox Code Playgroud)
哪种代码最适合使用(性能和速度副)?
您应该考虑代码大小,可读性,可理解性,可维护性,因此明确的赢家是......
所以我建议
Capatilize_City =
System.Globalization.CultureInfo.CurrentCulture.TextInfo
.ToTitleCase(City.ToLower());
Run Code Online (Sandbox Code Playgroud)