You want to capitalize your string by uppercasing the first letter, and then return it with the remaining part unchanged. Basically, you need the ucfirst function from PHP and Perl, which has the following results.
| Input | Output |
| samuel | Samuel |
| julia | Julia |
| john smith | John smith It does not uppercase each word. |
In this article, I am going to show you an example and benchmark of a C# method that uppercases the first letter. The method first here is the slower of the two.
using System;
class Program
{
static void Main()
{
Console.WriteLine(UppercaseFirst("samuel"));
Console.WriteLine(UppercaseFirst("julia"));
Console.WriteLine(UppercaseFirst("john smith"));
// Samuel
// Julia
// John smith
}
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);
}
}I investigated ToCharArray and its performance impact on this sort of character-based method. The following is the faster version, and it returns the same results.
using System;
class Program
{
static void Main()
{
Console.WriteLine(UppercaseFirst("samuel"));
Console.WriteLine(UppercaseFirst("julia"));
Console.WriteLine(UppercaseFirst("john smith"));
// Samuel
// Julia
// John smith
}
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);
}
}Here are my results from testing 1,000,000 iterations of these functions in a loop over the string "michael". This test is in my ASP.NET application, so the environment is the same as it will be in my ASP.NET app as it is updated on the Internet.
The second approach is faster because it only allocates one new string in the return statement. The first approach allocates two strings: the Substring(1), and then a new string with string.Concat. [See string.Concat link above]
These methods are valuable tools in your arsenal as a .NET developer. They are useful for database results that may not be formatted correctly. Custom logic for names such as "McCain" and "DeGeneres" can be added.
Normally, the performance requirements are not strict when you use this kind of code, but occasionally the benchmarks here may be useful. They can also help us understand how strings work in C#: they are immutable.