【问题标题】:How can I capitalize each first letter of a word in a sentence? [duplicate]如何将句子中单词的每个首字母大写? [复制]
【发布时间】:2011-02-21 23:52:55
【问题描述】:

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

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

这一项应该适当地大写每个单词。意思是,每个单词的第一个字母都应该大写。我无法让它工作。

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

感谢您的建议。

【问题讨论】:

  • @ChrisF:我不认为这是这个问题的重复。在另一个问题中,它询问是否将每个句子的第一个单词大写。在这里,我想将每个单词的第一个字母大写。由于我可以 .Split() 句子,我不需要正则表达式,但我的尝试没有奏效 - 因此问题。
  • @Thomas - 我的错。那么stackoverflow.com/questions/880597/… 怎么样?它与语言无关,但有一个 c# 解决方案。
  • 其他人已经回答了您的问题,但这里有一些建议。首先,您不能将char 转换为string,但myChar.ToString() 可以。其次,字符串是不可变的。您不能重新分配字符串中的任意字符(要这样做,请使用string.ToCharArray(),使用char 数组,然后在该数组上调用new string()
  • @Sapph:为什么 (string) 不起作用,但 ToString() 起作用? .ToString() 有什么不同?

标签: c# string char


【解决方案1】:

也许在TextInfo 类中使用ToTitleCase 方法

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

【讨论】:

  • 使用这段代码,我们每次都需要调用该方法。是否有任何覆盖方法可以强制每个文本框在离开时转换为标题大小写
  • 应该更新为使用 CultureInfo.CurrentCulture.TextInfo 而不是访问线程。见:msdn.microsoft.com/en-us/library/…
  • 另外值得注意的是 - 如果您的字符串全部为大写,则不会转换文本(它看起来像首字母缩写词)。使用textInfo.ToTitleCase(title.ToLower()) 获取标题大小写。
【解决方案2】:

我是这样做的:

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

【讨论】:

  • 您的解决方案显然太长了 - 他的机器一次不能复制粘贴超过 3 行;)
  • @Neurofluxation:傲慢的言论是怎么回事?互联网的匿名性使人从木制品中脱颖而出。
  • * smiles * 嗯,没有幽默感,我忘了
【解决方案3】:

试试这个:

        string inputString = "this is a test";

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

【讨论】:

  • 这是正确的现代答案。
猜你喜欢
  • 2010-11-12
  • 2012-05-20
  • 2015-11-10
  • 1970-01-01
  • 2014-07-11
  • 1970-01-01
  • 2021-08-08
  • 2020-08-30
相关资源
最近更新 更多