将字符串转换为标题格式
将字符串转换为标题格式
我有一个字符串,其中包含混合大小写字母的单词。
例如:string myData = \"a Simple string\";
我需要将每个单词(由空格分隔)的第一个字符转换为大写字母。所以我想要的结果是:string myData = \"A Simple String\";
有没有简单的方法可以做到这一点?我不想拆分字符串并进行转换(那将是我最后的手段)。此外,保证这些字符串是英语。
admin 更改状态以发布 2023年5月20日
尝试这个:
string myText = "a Simple string"; string asTitleCase = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo. ToTitleCase(myText.ToLower());
正如已经指出的那样,使用TextInfo.ToTitleCase可能不会给你想要的确切结果。如果你需要更多的控制输出,你可以像这样做:
IEnumerableCharsToTitleCase(string s) { bool newWord = true; foreach(char c in s) { if(newWord) { yield return Char.ToUpper(c); newWord = false; } else yield return Char.ToLower(c); if(c==' ') newWord = true; } }
然后像这样使用它:
var asTitleCase = new string( CharsToTitleCase(myText).ToArray() );
MSDN: TextInfo.ToTitleCase
确保包含:using System.Globalization
string title = "war and peace"; TextInfo textInfo = new CultureInfo("en-US", false).TextInfo; title = textInfo.ToTitleCase(title); Console.WriteLine(title) ; //War And Peace //When text is ALL UPPERCASE... title = "WAR AND PEACE" ; title = textInfo.ToTitleCase(title); Console.WriteLine(title) ; //WAR AND PEACE //You need to call ToLower to make it work title = textInfo.ToTitleCase(title.ToLower()); Console.WriteLine(title) ; //War And Peace