Sai A Sai A
Updated date Apr 03, 2024
In this blog, we explore three different approaches to converting strings to Pascal Case in C# using String.Split() and String.Join(), TextInfo.ToTitleCase(), and Regex.Replace().
  • 5.1k
  • 0
  • 0

Method 1: Using String.Split() and String.Join()

To convert a string to Pascal Case in C# by using the String.Split() and String.Join() methods. The basic idea is to split the input string into words, capitalize the first letter of each word, and join the words back together to form the output string. Here is the code example:

string input = "hello world";
string[] words = input.Split(' ');
for (int i = 0; i < words.Length; i++)
{
    string word = words[i];
    if (word.Length > 0)
    {
        char firstChar = char.ToUpper(word[0]);
        string restChars = word.Substring(1).ToLower();
        words[i] = firstChar + restChars;
    }
}
string output = string.Join("", words);

In this code , we first split the input string into an array of words using the space character as a separator. Then we loop through each word, capitalize the first letter, convert the rest of the letters to lowercase, and store the modified word back into the array. Finally, we join the array of words back together into a single string with no separator.

HelloWorld

Method 2: Using TextInfo.ToTitleCase()

The second approach to convert a string to Pascal Case in C# is by using the TextInfo.ToTitleCase() method. This method is part of the System.Globalization namespace and converts the input string to title case, which capitalizes the first letter of each word and converts the rest of the letters to lowercase. 

string input = "hello world";
string output = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input);

In this code example, we first set the input string to "hello world". Then we call the ToTitleCase() method on the TextInfo object of the current culture to convert the input string to title case, which is equivalent to Pascal Case. Finally, we store the result in the output variable.

Hello World

Method 3: Using Regex.Replace()

To convert a string to Pascal Case in C# by using the Regex.Replace() method. This method is part of the System.Text.RegularExpressions namespace and replaces all occurrences of a regular expression in a string with a specified replacement string. Here is the code example:

string input = "hello world";
string output = Regex.Replace(input, @"\b\w", m => m.Value.ToUpper());

In this code, we first set the input string to "hello world". Then we call the Replace() method on the Regex object to replace all occurrences of a word boundary followed by a word character with the uppercase version of the matched character. The lambda expression passed as the second argument to Replace() is used to perform the uppercase conversion. Finally, we store the result in the output variable.

HelloWorld

Comments (0)

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