How can I capitalize each first letter of a word in a sentence? [duplicate]
Possible Duplicate:
How to capitalize first letter of each sentence?
public static string CapitalizeEachWord(this string sentence)
{
string[] words = sentence.Split();
foreach (string word in words)
{
word[0] = ((string)word[0]).ToUpper();
}
}
I'm trying to create a extension method for a helper class I'm trying to create for myself for future projects.
This one particular is supposed to capitalize each word appropriately. Meaning, the first letter o开发者_JS百科f every word should be capitalized. I'm having trouble getting this to work.
It says I cannot convert a char to a string, but I remember being able to do that at some point. Maybe I'm forgetting a crucial part.
Thanks for the suggestions.
Maybe use the ToTitleCase
method in the TextInfo
class
How to convert strings to lower, upper, or title (proper) case by using Visual C#
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
Console.WriteLine(textInfo.ToTitleCase(title));
Here's how I do it:
public static string ProperCase(string stringToFormat)
{
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
// Check if we have a string to format
if (String.IsNullOrEmpty(stringToFormat))
{
// Return an empty string
return string.Empty;
}
// Format the string to Proper Case
return textInfo.ToTitleCase(stringToFormat.ToLower());
}
Try this:
string inputString = "this is a test";
string outputString = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(inputString);
精彩评论