我有一个带有文本框的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的答案。


当前回答

当你所需要的只是:

/// <summary>
/// Returns the input string with the first character converted to uppercase if a letter
/// </summary>
/// <remarks>Null input returns null</remarks>
public static string FirstLetterToUpperCase(this string s)
{
    if (string.IsNullOrWhiteSpace(s))
        return s;

    return char.ToUpper(s[0]) + s.Substring(1);
}

值得注意的点:

这是一个扩展方法。 如果输入是空的、空的或空白的,则输入按原样返回。 字符串。IsNullOrWhiteSpace是在. net Framework 4中引入的。这将不适用于旧的框架。

其他回答

对于第一个字母,带有错误检查:

public string CapitalizeFirstLetter(string s)
{
    if (String.IsNullOrEmpty(s))
        return s;
    if (s.Length == 1)
        return s.ToUpper();
    return s.Remove(1).ToUpper() + s.Substring(1);
}

这是一个方便的扩展

public static string CapitalizeFirstLetter(this string s)
{
    if (String.IsNullOrEmpty(s))
        return s;
    if (s.Length == 1)
        return s.ToUpper();
    return s.Remove(1).ToUpper() + s.Substring(1);
}

正如BobBeechey在回答这个问题时所建议的,下面的代码可以解决这个问题:

private void txt_fname_TextChanged(object sender, EventArgs e)
{
    char[] c = txt_fname.Text.ToCharArray();
    int j;
    for (j = 0; j < txt_fname.Text.Length; j++)
    {
        if (j==0) c[j]=c[j].ToString().ToUpper()[0];
        else c[j] = c[j].ToString().ToLower()[0];
    }
    txt_fname.Text = new string(c); 
    txt_fname.Select(txt_fname.Text.Length, 1);
}

正确的方法是使用文化:

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

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

最快的方法:

private string Capitalize(string s){
    if (string.IsNullOrEmpty(s))
    {
        return string.Empty;
    }
    char[] a = s.ToCharArray();
    a[0] = char.ToUpper(a[0]);
    return new string(a);
}

测试显示下一个结果(有1,000,000个符号作为输入的字符串):

测试结果

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

例子

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