I have a string which contains a mixture of upper and lower case characters, for example "a Simple string" . What I want to do is to convert first character of each word ( I can assume that words are separated by spaces) into upper case. So I want the result as "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.
Thanks..I didn't know that it is called title case.
Naveen
2009-07-30 11:35:39
Title case won't strictly convert EVERY word to have an uppercase starting letter, for example: and,but,or etc will remain lower. But I assume this is what you want anyway
Kirschstein
2009-07-30 11:37:52
True. Also, if a word is all upper case it doesn't work. eg - "an FBI agent shot my DOG" - > "An FBI Agent Shot My DOG". And it doesn't handle "McDonalds", and so forth.
Kobi
2009-07-30 11:41:25
@Kirschstein this function *does* conver these words to title case, even though they shouldn't be in English. See the documentation: `Actual result: "War And Peace"`.
Kobi
2009-07-30 11:44:59
+2
A:
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() );
Winston Smith
2009-07-30 11:34:08
+4
A:
http://support.microsoft.com/kb/312890 - How to convert strings to lower, upper, or title (proper) case by using Visual C#
ttarchala
2009-07-30 11:35:55