首先,我的所有城市都以大写形式返回,因此我将它们切换为小写.我怎样才能将第一个字母作为大写字母?谢谢你的帮助!
List<string> cities = new List<string>();
foreach (DataRow row in dt.Rows)
{
cities.Add(row[0].ToString().ToLower());
**ADDED THIS BUT NOTHING HAPPENED**
CultureInfo.CurrentCulture.TextInfo.ToTitleCase(row[0] as string);
}
return cities;
Run Code Online (Sandbox Code Playgroud)
Bri*_*ham 18
使用TextInfo.ToTitleCase方法:
System.Globalization.TextInfo.ToTitleCase();
Run Code Online (Sandbox Code Playgroud)
来自MSDN示例的一点,修改为使用OP的代码:
// Defines the string with mixed casing.
string myString = row[0] as String;
// Creates a TextInfo based on the "en-US" culture.
TextInfo myTI = new CultureInfo("en-US", false).TextInfo;
// Retrieve a titlecase'd version of the string.
string myCity = myTI.ToTitleCase(myString);
Run Code Online (Sandbox Code Playgroud)
全部在一行:
string myCity = new CultureInfo("en-US", false).TextInfo.ToTitleCase(row[0] as String);
Run Code Online (Sandbox Code Playgroud)
小智 3
正则表达式可能看起来有点长,但是有效
List<string> cities = new List<string>();
foreach (DataRow row in dt.Rows)
{
string city = row[0].ToString();
cities.Add(String.Concat(Regex.Replace(city, "([a-zA-Z])([a-zA-Z]+)", "$1").ToUpper(System.Globalization.CultureInfo.InvariantCulture), Regex.Replace(city, "([a-zA-Z])([a-zA-Z]+)", "$2").ToLower(System.Globalization.CultureInfo.InvariantCulture)));
}
return cities;
Run Code Online (Sandbox Code Playgroud)