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


当前回答

我想提供一个“最大性能”的答案。在我看来,“最大性能”的答案抓住了所有的场景,并提供了解释这些场景的问题的答案。所以,这是我的答案。原因如下:

IsNullOrWhiteSpace accounts for strings that are just spaces or null/empty. .Trim() removes white space from the front and back of the string. .First() takes the first element of an IEnumerable<TSource> (or string). We should check to see if it is a letter that can/should be uppercase. We then add the rest of the string, only if the length indicates we should. By .NET best practice, we should provide a culture under System.Globalization.CultureInfo. Providing them as optional parameters makes this method totally reusable, without having to type the chosen culture every time. I also noticed that my and most of these answers did not maintain the whitespace at the beginning of the string. This will also show how to maintain that whitespace. //Capitalize the first letter disregard all chars using regex. public static string RegCapString(this string instring, string culture = "en-US", bool useSystem = false) { if (string.IsNullOrWhiteSpace(instring)) { return instring; } var m = Regex.Match(instring, "[A-Za-z]").Index; return instring.Substring(0, m) + instring[m].ToString().ToUpper(new CultureInfo(culture, useSystem)) + instring.Substring(m + 1); } //Capitalize first char if it is a letter disregard white space. public static string CapString(this string instring, string culture = "en-US", bool useSystem = false) { if (string.IsNullOrWhiteSpace(instring) || !char.IsLetter(instring.Trim().First())) { return instring; } var whiteSpaces = instring.Length - instring.TrimStart().Length; return (new string(' ', whiteSpaces)) + instring.Trim().First().ToString().ToUpper(new CultureInfo(culture, useSystem)) + ((instring.TrimStart().Length > 1) ? instring.Substring(whiteSpaces + 1) : ""); }

其他回答

下面是对我有用的代码:

private string StringLetterUppercase(string input)
{
    if (input == null)
    {
        throw new ArgumentNullException(nameof(input));
    }
    else if (input == "")
    {
        throw new ArgumentException($"{nameof(input)} cannot be empty", nameof(input));
    }
    else
    {
        return input.First().ToString().ToUpper() + input.Substring(1);
    }
}
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());
}

首字母大写最简单的方法是:

使用System.Globalization; //创建一个基于"en-US"区域性的TextInfo。 TextInfo myTI = new CultureInfo("en-US", false)。 myTI.ToTitleCase (textboxname.Text)

我们可以这样做(c# 8.0, .NET 5):

input?.Length > 0 ? char.ToUpperInvariant(input[0]) + input[1..] : input

我相信这足够短,可以做内联。


如果input是一个空字符串,我们得到一个空字符串。如果input为null,则得到null。

否则,代码接受第一个字符输入[0],并使用char.ToUpperInvariant将其转换为大写。并连接其余的输入[1..]。

编译器会将范围访问转换为对Substring的调用,而且它可以利用我们已经获得了长度的事实。

与公认的答案相比,这样做的优点是不使用LINQ。其他一些答案将字符串转换为数组,只取第一个字符。这段代码也没有做到这一点。


如果你喜欢扩展方法,你可以这样做:

public static string FirstCharToUpper(this string input) =>
        input?.Length > 0 ? char.ToUpperInvariant(input[0]) + input[1..] : input;

如果你更喜欢扔呢?好的,让它扔:

public static string FirstCharToUpper(this string input) =>
        input switch
        {
            null => throw new ArgumentNullException(nameof(input)),
            _ => input.Length > 0 ? char.ToUpperInvariant(input[0]) + input[1..] : input
        };

这里是大致相同的代码(因为我们正在创建一个扩展方法,所以我们可以更详细一点):

public static string FirstCharToUpperEquivalent(this string input)
{
    if (input == null)
    {
        throw new ArgumentNullException(nameof(input));
    }

    var length = input.Length;
    if (length == 0)
    {
        return input;
    }

    string firstCharacter = char.ToUpperInvariant(input[0]).ToString();
    return string.Concat(firstCharacter, input.Substring(1, length - 1));
}

我做了1000轮155个单词的基准测试(所以它们被调用了155000次),结果是:

Benchmarking type Tests
  TestAccepted         00:00:00.0465979
  TestProposalNoThrow  00:00:00.0092839
  TestProposalDoThrow  00:00:00.0092938
  TestProposalEquival  00:00:00.0091463

我在Windows 10、英特尔酷睿i3上运行它,使用Jon Skeet用c#编写的简单微基准测试代码。

这就可以了,尽管它也会确保没有错误的大写字母不是在单词的开头。

public string(string s)
{
    System.Globalization.CultureInfo c = new System.Globalization.CultureInfo("en-us", false)
    System.Globalization.TextInfo t = c.TextInfo;

    return t.ToTitleCase(s);
}