Casing Strings

You can change the casing of a string. For example, a string composing of lowercase letters can be transformed into all caps. We use the ToUpper() and ToLower() instance methods which returns an uppercase or lowercase version of the string.

string lowercase = "abc";
string uppercase = "ABC";

Console.WriteLine("lowercase.ToUpper() = " + lowercase.ToUpper());
Console.WriteLine("uppercase.ToLower() = " + uppercase.ToLower());
lowercase.ToUpper() = ABC
uppercase.ToLower() = abc

Note that if a string has different cases, such as a sentence where the first character is in uppercase and the rest is in lowercase, then using ToUpper() only changes the case of the characters in lowercase and does not affect the ones which are already in uppercase. Same goes with the ToLower() method.

Let’s apply what we have learned by creating a function that converts a sentence into Title Case, that is, every word starts with a capital letter. The following program uses some of the string manipulation methods we have learned so far.

class Program
{
    static string ToTitleCase(string str)
    {
        string[] words = str.Split(' ');

        for(int i = 0; i < words.Length; i++)
        {
            string firstLetter = words[i].Substring(0, 1);
            string rest = words[i].Substring(1);
            string result = firstLetter.ToUpper() + rest.ToLower();
            words[i] = result;
        }

        return String.Join(" ", words);
    }

    static void Main()
    {
        string input;

        Console.WriteLine("Enter a string: ");
        input = Console.ReadLine();

        Console.WriteLine("Converting to Title Case...");
        input = ToTitleCase(input);

        Console.WriteLine(input);
    }
}
Enter a string:
tHe quICK bROwN fOx
Converting to Title Case...
The Quick Brown Fox

We created a function named ToTitleCase which accepts one string argument which is the string that will be modified.

string[] words = str.Split(' ');

We first split the strings into multiple words so we can manipulate each word. We then enter a for loop to loop through all the words.

string firstLetter = words[i].Substring(0, 1);
string rest = words[i].Substring(1);

We then extract the first letter of the word and put it in a variable for later use. We also extract the rest of the letters of the word.

string result = firstLetter.ToUpper() + rest.ToLower();

We combine the extracted strings, but we used the ToUpper for the first letter and ToLower for the rest of the word. After that, we replaced the content of the current element of the array with the modified word.

return String.Join(" ", words);

Now, we combine the modified words and put spaces between these words. We then return it to the caller.