How can I capitalize each first letter of a word i

2019-02-08 23:44发布

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 of 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.

标签: c# string char
3条回答
老娘就宠你
2楼-- · 2019-02-09 00:04

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));
查看更多
Summer. ? 凉城
3楼-- · 2019-02-09 00:12

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());
}   
查看更多
Anthone
4楼-- · 2019-02-09 00:15

Try this:

        string inputString = "this is a test";

        string outputString = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(inputString);
查看更多
登录 后发表回答