Converting string to title case
I have a string which contains words in a mixture of upper and lower case characters.
For example: string myData = "a Simple string";
I need to convert the first character of each word (separated by spaces) into upper case. So I want the result as: string myData ="A Simple String";
Is there any easy way to do this? I don't want to split the string and do the conversion (that will be my last resort). Also, it is guaranteed that the strings are in English.
MSDN : TextInfo.ToTitleCase
Make sure that you include: 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
Try this:
string myText = "a Simple string";
string asTitleCase =
System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.
ToTitleCase(myText.ToLower());
As has already been pointed out, using TextInfo.ToTitleCase might not give you the exact results you want. If you need more control over the output, you could do something like this:
IEnumerable<char> CharsToTitleCase(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;
}
}
And then use it like so:
var asTitleCase = new string( CharsToTitleCase(myText).ToArray() );
Yet another variation. Based on several tips here I've reduced it to this extension method, which works great for my purposes:
public static string ToTitleCase(this string s) {
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());
}
链接地址: http://www.djcxy.com/p/21026.html
上一篇: 使字符串大写的第一个字母(具有最高性能)
下一篇: 将字符串转换为标题大小写