我有一个带有文本框的DetailsView 我希望输入的数据总是以大写的第一个字母保存。

例子:

"red" --> "Red"
"red house" --> " Red house"

我怎样才能实现性能最大化呢?


注意:

Based on the answers and the comments under the answers, many people think this is asking about capitalizing all words in the string. E.g. => Red House It isn't, but if that is what you seek, look for one of the answers that uses TextInfo's ToTitleCase method. (Note: Those answers are incorrect for the question actually asked.) See TextInfo.ToTitleCase documentation for caveats (doesn't touch all-caps words - they are considered acronyms; may lowercase letters in middle of words that "shouldn't" be lowered, e.g., "McDonald" → "Mcdonald"; not guaranteed to handle all culture-specific subtleties re capitalization rules.)


注意:

第一个字母之后的字母是否必须小写,这个问题很模糊。公认的答案假定只有第一个字母需要修改。如果要强制字符串中除第一个字母外的所有字母都小写,请查找包含ToLower且不包含ToTitleCase的答案。


当前回答

用这种方法,你可以把每个单词的第一个字符抬高。

例子

"HeLlo wOrld" => "HeLlo wOrld"

public static string FirstCharToUpper(string input)
{
    if (String.IsNullOrEmpty(input))
        throw new ArgumentException("Error");
    return string.Join(" ", input.Split(' ').Select(d => d.First().ToString().ToUpper() +  d.ToLower().Substring(1)));
}

其他回答

如果性能/内存使用是一个问题,那么它只创建一个(1)StringBuilder和一个(1)与原始字符串相同大小的新String。

public static string ToUpperFirst(this string str) {
  if(!string.IsNullOrEmpty(str)) {
    StringBuilder sb = new StringBuilder(str);
    sb[0] = char.ToUpper(sb[0]);

    return sb.ToString();

  } else return str;
}

扩展Carlos上面的问题,如果你想要大写多个句子,你可以使用下面的代码:

    /// <summary>
    /// Capitalize first letter of every sentence. 
    /// </summary>
    /// <param name="inputSting"></param>
    /// <returns></returns>
    public string CapitalizeSentences (string inputSting)
    {
        string result = string.Empty;
        if (!string.IsNullOrEmpty(inputSting))
        {
            string[] sentences = inputSting.Split('.');

            foreach (string sentence in sentences)
            {
                result += string.Format ("{0}{1}.", sentence.First().ToString().ToUpper(), sentence.Substring(1)); 
            }
        }

        return result; 
    }

解决问题的可能方法:

   public static string FirstToUpper(this string lowerWord)
   {
       if (string.IsNullOrWhiteSpace(lowerWord) || string.IsNullOrEmpty(lowerWord))
            return lowerWord;
       return new StringBuilder(lowerWord.Substring(0, 1).ToUpper())
                 .Append(lowerWord.Substring(1))
                 .ToString();
   }

正确的方法是使用文化:

System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(word.ToLower())

注意:这将大写字符串中的每个单词,例如:“红房子”——>“红房子”。该解决方案还将减少单词中的大写字母,例如:"old McDonald"——> "old McDonald"。

最简单和最快的方法是将字符串的第一个字符替换为大写字符:

string str = "test";<br>
str = str.Replace(str[0], char.ToUpper(str[0]));