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


当前回答

这是最快的方法:

public static unsafe void ToUpperFirst(this string str)
{
    if (str == null)
        return;
    fixed (char* ptr = str)
        *ptr = char.ToUpper(*ptr);
}

在不改变原始字符串的情况下:

public static unsafe string ToUpperFirst(this string str)
{
    if (str == null)
        return null;
    string ret = string.Copy(str);
    fixed (char* ptr = ret)
        *ptr = char.ToUpper(*ptr);
    return ret;
}

其他回答

FluentSharp有lowerCaseFirstLetter方法来做这个。

public string FirstLetterToUpper(string str)
{
    if (str == null)
        return null;

    if (str.Length > 1)
        return char.ToUpper(str[0]) + str.Substring(1);

    return str.ToUpper();
}

旧的回答: 这使得每个首字母都是大写的

public string ToTitleCase(string str)
{
    return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
}

试试这个:

static public string UpperCaseFirstCharacter(this string text) {
    return Regex.Replace(text, "^[a-z]", m => m.Value.ToUpper());
}
 private string capitalizeFirstCharacter(string format)
 {
     if (string.IsNullOrEmpty(format))
         return string.Empty;
     else
         return char.ToUpper(format[0]) + format.ToLower().Substring(1);
 }

最近我有一个类似的需求,并记得LINQ函数Select()提供了一个索引:

string input;
string output;

input = "red house";
output = String.Concat(input.Select((currentChar, index) => index == 0 ? Char.ToUpper(currentChar) : currentChar));
//output = "Red house"

因为我经常需要它,所以我为字符串类型做了一个扩展方法:

public static class StringExtensions
{
    public static string FirstLetterToUpper(this string input)
    {
        if (string.IsNullOrEmpty(input))
            return string.Empty;
        return String.Concat(input.Select((currentChar, index) => index == 0 ? Char.ToUpper(currentChar) : currentChar));
    }
}

请注意,只有第一个字母被转换为大写字母,其余所有字符都不会被更改。如果你需要其他字符小写,你也可以为索引> 0调用Char.ToLower(currentChar),或者首先在整个字符串上调用ToLower()。

关于性能,我将代码与Darren的解决方案进行了比较。在我的机器上,Darren的代码大约快了两倍,这并不奇怪,因为他只直接编辑char数组中的第一个字母。

所以我建议你采用达伦的代码,如果你需要最快的解决方案。如果您想集成其他字符串操作,那么让lambda函数的表达能力触及输入字符串的字符可能会很方便——您可以轻松地扩展这个函数——所以我把这个解决方案留在这里。