开发者

How can I capitalize each first letter of a word in a sentence? [duplicate]

This question already has answers here: Closed 11 years ago.

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜