SoFunction
Updated on 2025-03-06

Example of C# method to implement capitalization of strings

Recently, I encountered a need in my work, and I need to capitalize the first letter of a string, so I found some methods to capitalize the first character of a string with you. I won’t say much about it below, let’s take a look at the detailed introduction together.

If you need to convert the string "red" to "Red", and convert "red house" to "Red house" or the first capitalization of the word, the following is the technology I saw from the Internet.

public static string FirstCharToUpper(string input)
{
 if ((input))
  throw new ArgumentException("ARGH!");
 return ().ToString().ToUpper() + (1);
}

This method is to get the first character and add the following characters. You can see that this method requires three strings in memory.

public string FirstLetterToUpper(string str)
{
 if (str == null)
  return null;
 if ( > 1)
  return (str[0]) + (1);
 return ();
}

This method also requires two strings.

The following method is probably rare to discover, which is the CultureInfo method

(());

This method is a better method. If I type "red house" then it will be converted to "Red House"

This method can also be used in the above method

CultureInfo("en-US").("red house");

If you need to use splicing, you can use this method

(1).ToUpper() + (1)

The above method will not convert "red house" to "Red house"

Here is a better method

char[] a = ();
  a[0] = (a[0]);
  return new string(a);

If you need many strings to capitalize the first capitalization like this, you can use the following method

string str = "red house";
   ((str, "^[a-z]", m => ()));

The same method as above, you can use another function

(str, @"^\w", t => ());

If you want the best speed, please use the following method

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

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.