Home
C#
String Uppercase First Letter
This page was last reviewed on Apr 20, 2023.
Dot Net Perls
Uppercase first letter. Strings sometimes have lowercase first letters. Uppercasing the first letter is often necessary. The result string has its first letter uppercased.
Strings with multiple words can be changed to title case. We can capitalize "Multiple Words." When we need to handle words, we have more complex logic.
String Change Characters
First example. This method returns correctly uppercased strings. We provide an example of a static method that uppercases the first letter.
Info To avoid processing an empty string (which would cause an exception) we invoke the IsNullOrEmpty method.
string.IsNullOrEmpty
using System; class Program { static void Main() { Console.WriteLine(UppercaseFirst("houston")); Console.WriteLine(UppercaseFirst("dallas")); Console.WriteLine(UppercaseFirst("austin")); } static string UppercaseFirst(string s) { // Check for empty string. if (string.IsNullOrEmpty(s)) { return string.Empty; } // Return char and concat substring. return char.ToUpper(s[0]) + s.Substring(1); } }
Houston Dallas Austin
Example 2. Next, we look at a method that uses the ToCharArray method instead. We investigate ToCharArray and its performance impact on this kind of character-based method.
String ToCharArray
using System; class Program { static void Main() { Console.WriteLine(UppercaseFirst("quebec")); } static string UppercaseFirst(string s) { if (string.IsNullOrEmpty(s)) { return string.Empty; } char[] a = s.ToCharArray(); a[0] = char.ToUpper(a[0]); return new string(a); } }
Quebec
Uppercase words. This program defines a method named UppercaseWords that is equivalent to the ucwords function in PHP. UppercaseWords converts the string to a character array buffer.
char Array
Note Internally, the method body of this method first tests the first character of the string.
And It special-cases the first character because the loop in the next part does not correctly allow for the first character.
Detail UppercaseWords does a for-loop through all the characters in the string starting at the second character with index of one.
for
Finally In each iteration UppercaseWords tests the previous character for a space. If it detects a space, it modifies the character array buffer.
using System; class Program { static string UppercaseWords(string value) { char[] array = value.ToCharArray(); // Handle the first letter in the string. if (array.Length >= 1) { if (char.IsLower(array[0])) { array[0] = char.ToUpper(array[0]); } } // Scan through the letters, checking for spaces. // ... Uppercase the lowercase letters following spaces. for (int i = 1; i < array.Length; i++) { if (array[i - 1] == ' ') { if (char.IsLower(array[i])) { array[i] = char.ToUpper(array[i]); } } } return new string(array); } static void Main() { // Uppercase words in these strings. const string value1 = "something in the way"; const string value2 = "dot net PERLS"; const string value3 = "String_two;three"; const string value4 = " sam"; // ... Compute the uppercase strings. Console.WriteLine(UppercaseWords(value1)); Console.WriteLine(UppercaseWords(value2)); Console.WriteLine(UppercaseWords(value3)); Console.WriteLine(UppercaseWords(value4)); } }
Something In The Way Dot Net PERLS String_two;three Sam
Benchmark. What is the fastest way to uppercase the first letter in a string? We compare the 2 versions of UppercaseFirst in a benchmark program.
Version 1 This version of the code uses Substring and a concatenation of a char and the result of Substring.
Version 2 This code uses the ToCharArray method, and avoids an allocation because it has no concatenation.
Result Version 2 is faster because it avoids a concatenation of 2 strings. It should be preferred in most programs.
return
String Substring
string.Concat
using System; using System.Diagnostics; class Program { static string UppercaseFirst(string s) { if (string.IsNullOrEmpty(s)) { return string.Empty; } return char.ToUpper(s[0]) + s.Substring(1); } static string UppercaseFirst2(string s) { if (string.IsNullOrEmpty(s)) { return string.Empty; } char[] a = s.ToCharArray(); a[0] = char.ToUpper(a[0]); return new string(a); } const int _max = 1000000; static void Main() { var s1 = Stopwatch.StartNew(); // Version 1: test first method. for (int i = 0; i < _max; i++) { if (UppercaseFirst("denver") != "Denver") { return; } } s1.Stop(); var s2 = Stopwatch.StartNew(); // Version 2: test second method. for (int i = 0; i < _max; i++) { if (UppercaseFirst2("denver") != "Denver") { return; } } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } }
60.66 ns UppercaseFirst 42.66 ns UppercaseFirst2
Notes, performance. The UppercaseWords method could be implemented by first splitting on the sub-words. But this would result in more allocations.
String Split
However You could use the Regex.Split method for a better algorithm of breaking up the words.
Regex.Split
Note The method does not contain sophisticated error correction. It may incorrectly handle some words.
ToTitleCase. We do not always need a custom method for uppercasing the first letter in each word in a string. We can use ToTitleCase method on the TextInfo type.
String ToTitleCase
A summary. We looked at methods that uppercase the first character in strings. They are useful for data that may not be correctly formatted. Custom logic for certain names can be added.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 20, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.