Sai A Sai A
Updated date Apr 03, 2024
In this blog, we will cover multiple ways to convert strings to title case in C# using built-in methods, regular expressions, LINQ, and custom methods.
  • 1.4k
  • 0
  • 0

Convert Strings to Title Case in C#:

Title casing is a method of capitalizing the first letter of every word in a sentence, except for certain words such as conjunctions, prepositions, and articles. In this blog, we will discuss different ways to convert strings to title case in C#

Method 1: Using TextInfo.ToTitleCase Method

The first method we will discuss is using the built-in TextInfo.ToTitleCase method. This method is available in the System.Globalization namespace and can be used to convert a string to title case. The TextInfo.ToTitleCase method uses a set of rules to determine which words should be capitalized and which ones should not.

using System.Globalization;

string input = "the quick brown fox jumps over the lazy dog";
TextInfo textInfo = CultureInfo.CurrentCulture.TextInfo;
string output = textInfo.ToTitleCase(input);

Console.WriteLine(output);

Output:

"The Quick Brown Fox Jumps Over The Lazy Dog"

Method 2: Using String.Split and String.Join Methods

To convert a string to title case by using the String.Split and String.Join methods. This method involves splitting the string into individual words, capitalizing the first letter of each word, and then joining the words back together.

string input = "the quick brown fox jumps over the lazy dog";
string[] words = input.Split(' ');
for (int i = 0; i < words.Length; i++)
{
    words[i] = words[i][0].ToString().ToUpper() + words[i].Substring(1);
}
string output = String.Join(' ', words);

Console.WriteLine(output);

Output:

"The Quick Brown Fox Jumps Over The Lazy Dog"

Method 3: Using Regular Expressions

Regular expressions can also be used to convert a string to title case. This method involves using regular expressions to find each word in the string and capitalize the first letter of each word.

Here's the sample code for using regular expressions:

using System.Text.RegularExpressions;

string input = "the quick brown fox jumps over the lazy dog";
string output = Regex.Replace(input, @"\b(\w)", m => m.Value.ToUpper());

Console.WriteLine(output);

Output:

"The Quick Brown Fox Jumps Over The Lazy Dog"

Method 4: Using LINQ

To convert a string to title case is by using LINQ. This method involves splitting the string into individual words, capitalizing the first letter of each word, and then joining the words back together using LINQ.

string input = "the quick brown fox jumps over the lazy dog";
string output = String.Join(' ', input.Split(' ')
                        .Select(word => word.Substring(0, 1).ToUpper() + word.Substring(1)));

Console.WriteLine(output);

Output:

 "The Quick Brown Fox Jumps Over The Lazy Dog"

Comments (0)

There are no comments. Be the first to comment!!!