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


当前回答

我从c#大写首字母- Dot Net Perls中获得了最快的方法,并将其转换为扩展方法:

    /// <summary>
    /// Returns the input string with the first character converted to uppercase, or mutates any nulls passed into string.Empty
    /// </summary>
    public static string FirstLetterToUpperCaseOrConvertNullToEmptyString(this string s)
    {
        if (string.IsNullOrEmpty(s))
            return string.Empty;

        char[] a = s.ToCharArray();
        a[0] = char.ToUpper(a[0]);
        return new string(a);
    }

注意:使用ToCharArray比替代char.ToUpper(s[0]) + s.Substring(1)更快的原因是只分配了一个字符串,而Substring方法为子字符串分配了一个字符串,然后再分配一个字符串来组成最终结果。


下面是这种方法的样子,结合CarlosMuñoz接受的答案的初始测试:

    /// <summary>
    /// Returns the input string with the first character converted to uppercase
    /// </summary>
    public static string FirstLetterToUpperCase(this string s)
    {
        if (string.IsNullOrEmpty(s))
            throw new ArgumentException("There is no first letter");

        char[] a = s.ToCharArray();
        a[0] = char.ToUpper(a[0]);
        return new string(a);
    }

其他回答

第一个字母和空格后面的每个字母都大写,其他字母都小写。

public string CapitalizeFirstLetterAfterSpace(string input)
{
    System.Text.StringBuilder sb = new System.Text.StringBuilder(input);
    bool capitalizeNextLetter = true;
    for(int pos = 0; pos < sb.Length; pos++)
    {
        if(capitalizeNextLetter)
        {
            sb[pos]=System.Char.ToUpper(sb[pos]);
            capitalizeNextLetter = false;
        }
        else
        {
            sb[pos]=System.Char.ToLower(sb[pos]);
        }

        if(sb[pos]=' ')
        {
            capitalizeNextLetter=true;
        }
    }
}

正确的方法是使用文化:

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

使用string.Create()并在方法中避免使用throw关键字(是的,您没有看错),我们可以进一步采用Marcell的答案。此外,我的方法处理任意长度的字符串(例如,几兆字节的文本)。

public static string L33t(this string s)
{
    static void ThrowError() => throw new ArgumentException("There is no first letter");

    if (string.IsNullOrEmpty(s))
        ThrowError();                      // No "throw" keyword to avoid costly IL

    return string.Create(s.Length, s, (chars, state) =>
    {
        state.AsSpan().CopyTo(chars);      // No slicing to save some CPU cycles
        chars[0] = char.ToUpper(chars[0]);
    });
}

性能

下面是在。net Core 3.1.7 64位上运行的基准测试的数据。我添加了一个更长的字符串,以精确计算额外拷贝的成本。

Method Data Mean Error StdDev Median
L33t red 8.545 ns 0.4612 ns 1.3308 ns 8.075 ns
Marcell red 9.153 ns 0.3377 ns 0.9471 ns 8.946 ns
L33t red house 7.715 ns 0.1741 ns 0.4618 ns 7.793 ns
Marcell red house 10.537 ns 0.5002 ns 1.4351 ns 10.377 ns
L33t red r(...)house [89] 11.121 ns 0.6774 ns 1.9106 ns 10.612 ns
Marcell red r(...)house [89] 16.739 ns 0.4468 ns 1.3033 ns 16.853 ns

完整的测试代码

using System;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

namespace CorePerformanceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var summary = BenchmarkRunner.Run<StringUpperTest>();
        }
    }

    public class StringUpperTest
    {
        [Params("red", "red house", "red red red red red red red red red red red red red red red red red red red red red house")]
        public string Data;

        [Benchmark]
        public string Marcell() => Data.Marcell();

        [Benchmark]
        public string L33t() => Data.L33t();
    }

    internal static class StringExtensions
    {
        public static string Marcell(this string s)
        {
            if (string.IsNullOrEmpty(s))
                throw new ArgumentException("There is no first letter");

            Span<char> a = stackalloc char[s.Length];
            s.AsSpan(1).CopyTo(a.Slice(1));
            a[0] = char.ToUpper(s[0]);
            return new string(a);
        }

        public static string L33t(this string s)
        {
            static void ThrowError() => throw new ArgumentException("There is no first letter");

            if (string.IsNullOrEmpty(s))
                ThrowError(); // IMPORTANT: Do not "throw" here!

            return string.Create(s.Length, s, (chars, state) =>
            {
                state.AsSpan().CopyTo(chars);
                chars[0] = char.ToUpper(chars[0]);
            });
        }
    }
}

如果你能让它更快,请告诉我!

FluentSharp有lowerCaseFirstLetter方法来做这个。