The other day I was converting some "utility" classes to be used within my Silverlight project and I realized (well, the compiler told me) that the ToTitleCase method was missing from System.Globalization.TextInfo. So I created one that ended up being more useful then the original one (well, for my own usage).
The default utility of ToTitleCase is obviously to change the first letter to uppercase and the rest to lowercase (mine can take a complete sentence too). Then a friend of mine gave me a case where it wouldn't work. Take for example "Merriam-Webster"; the W after the dash will be lower case. That's why I added a parameter to my ToTitleCase method, a character list, that are used as "uppercase after this character". The default value is naturally " " (space).
While I was there, I used the new Method Extensions feature. So it can be used like:
"this sentence to titlecase".ToTitleCase();
1: public static class UtilsClient
2: { 3: public static string ToTitleCase(this string value)
4: { 5: return ToTitleCase(value, new List<char> { ' ' }); 6: }
7:
8: public static string ToTitleCase(this string value, List<char> separators)
9: { 10: string result = "";
11: bool nextUpper = true; //first letter always upper case
12:
13: value = value.ToLower();//initialize all to lower case
14:
15: for (int charIndex = 0; charIndex < value.Length; charIndex++)
16: { 17: string nextChar = value[charIndex].ToString();
18: if (nextUpper)
19: { 20: nextChar = nextChar.ToUpper();
21: }
22:
23: result += nextChar;
24:
25: if (separators.Any(c => c.Equals(value[charIndex])))//put next char to upper case
26: nextUpper = true;
27: else
28: nextUpper = false;
29:
30: }
31:
32: return result;
33: }
34: }