Converting string to title case
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) =>
CultureInfo.InvariantCulture.TextInfo.ToTitleCase(s.ToLower());
Personally I tried the TextInfo.ToTitleCase
method, but, I don´t understand why it doesn´t work when all chars are upper-cased.
Though I like the util function provided by Winston Smith, let me provide the function I'm currently using:
public static String TitleCaseString(String s)
{
if (s == null) return s;
String[] words = s.Split(' ');
for (int i = 0; i < words.Length; i++)
{
if (words[i].Length == 0) continue;
Char firstChar = Char.ToUpper(words[i][0]);
String rest = "";
if (words[i].Length > 1)
{
rest = words[i].Substring(1).ToLower();
}
words[i] = firstChar + rest;
}
return String.Join(" ", words);
}
Playing with some tests strings:
String ts1 = "Converting string to title case in C#";
String ts2 = "C";
String ts3 = "";
String ts4 = " ";
String ts5 = null;
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts1)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts2)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts3)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts4)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts5)));
Giving output:
|Converting String To Title Case In C#|
|C|
||
| |
||
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() );