Home >Backend Development >C++ >How to Efficiently Capitalize the First Letter of a String in C#?

How to Efficiently Capitalize the First Letter of a String in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-16 13:22:59111browse

How to Efficiently Capitalize the First Letter of a String in C#?

Capitalize the first letter of C# strings: Performance optimization solution

Problem description:

In DetailsView with a textbox, you need to ensure that the input data is always saved starting with a capital letter while maximizing performance.

Optimization plan:

For best performance, it is recommended to use the FirstCharToUpper() extension method in the provided C# code. This method has been optimized for several versions of C#, including:

<code class="language-csharp">public static string FirstCharToUpper(this string input)
{
    return input switch
    {
        null => throw new ArgumentNullException(nameof(input)),
        "" => throw new ArgumentException($"{nameof(input)} cannot be empty", nameof(input)),
        _ => string.Concat(input[0].ToString().ToUpper(), input.AsSpan(1))
    };
}</code>

Usage:

<code class="language-csharp">string input = "red";
string capitalized = input.FirstCharToUpper();</code>

This solution avoids unnecessary memory allocation by using ReadonlySpan and switch statements. It also uses string.Concat() to avoid string concatenation.

Note:

This method assumes that only the first letter should be capitalized. If you want to force all letters after the first letter to be lowercase, use the answer that contains ToLower but not To.

The above is the detailed content of How to Efficiently Capitalize the First Letter of a String in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn