c# - 将字符串中单词的第一个字符大写

标签 c# performance

我想将我的字符串格式化为大写字符格式(即大写单词的第一个字符)。

For Example - 
              If Input is: "NEW YORK CITY"
              then the desired output is: "New York City"

*我的字符串最多有 3 个单词。

之后,用谷歌搜索我发现了几种实现这种方法的方法,但我不知道哪种方法是最好的。

方法一:

string City = "NEW YORK CITY";
City = City.ToLower();
string Capatilize_City = "";
Capatilize_City = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(City);

Demo : Ideone with 1st method

方法二:

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();

Demo: Ideone with 2nd method

哪种代码最适合使用(性能和速度副)?

最佳答案

您应该关注代码大小、可读性、可理解性、可维护性,因此明显的赢家是...


编辑

所以我建议

Capatilize_City =
  System.Globalization.CultureInfo.CurrentCulture.TextInfo
      .ToTitleCase(City.ToLower());

关于c# - 将字符串中单词的第一个字符大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27978506/

相关文章:

php - 如何优化服务器上​​的 html、css 运行时以获得更好的加载时间?

在 where 子句中添加 'or' 后 MySql 性能变慢

c# - 我应该用 C/C++ 重写我的 DSP 例程,还是我擅长使用 C# 不安全指针?

c# - 如何将 Azure 移动服务与 Cordova 项目 AngularJS 和 C# 一起使用?

c# - 从字符串中获取数字

c# - Azure 弹性数据库合并 GUI key 碎片

performance - CVS 性能

c# - 通过 SOCKET 发送文件

c# - 基类还是普通类?

ruby-on-rails - 提高 24 小时内返回相同结果的 SQL 查询的性能