我想将字符串格式化为大写字符格式(即首字母大写)。将字符串中的第一个字符大写首字母大写
For Example -
If Input is: "NEW YORK CITY"
then the desired output is: "New York City"
*我的字符串最多有3个单词。
之后,谷歌搜索它,我发现了几种方法来实现这种方法,但我不明白这是最好的办法。
方法1:
string City = "NEW YORK CITY";
City = City.ToLower();
string Capatilize_City = "";
Capatilize_City = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(City);
法第二:
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();
w ^这些代码最适合使用(性能和速度副作用)?
你的第二种方法有很多分配,所以我的猜测是它会变慢。分析器可以给你要告诉的数据。 –
尽量避免手动。使用方法1。它也是可读且更短的。 – Amit
知道哪个更快的唯一方法就是测试它们。机会都很快,在这种情况下更简单一些。 – dbc