如何将句子中每个单词的首字母大写?

时间:2011-02-21 15:41:13

标签: c# string char

  

可能重复:
  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();                
    }
}

我正在尝试为我自己为未来项目创建的帮助程序类创建一个扩展方法。

这个特定应该适当地利用每个单词。意思是,每个单词的第一个字母都应该大写。我无法解决这个问题。

它说我无法将字符串转换为字符串,但我记得在某些时候能够做到这一点。也许我忘了关键部分。

感谢您的建议。

3 个答案:

答案 0 :(得分:22)

也许使用ToTitleCase

中的TextInfo方法

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

答案 1 :(得分:9)

我是这样做的:

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());
}   

答案 2 :(得分:6)

试试这个:

        string inputString = "this is a test";

        string outputString = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(inputString);