OneBite.Dev - Coding blog in a bite size

Capitalize A String In C#

Code snippet for how to Capitalize A String In C# with sample and detail explanation

In programming, it’s common to require that specific portions of text be in uppercase or capitalize. In the C# language, this process can be achieved quite simply. This article will provide a brief example of how to capitalize a string in C#.

Code Snippet: Capitalize A String In C#

The following example can be a quick reference guide.

string sentence = "capitalize a string in csharp";
TextInfo myTI = new CultureInfo("en-US", false).TextInfo;
sentence = myTI.ToTitleCase(sentence);
Console.WriteLine(sentence);

Code Explanation for Capitalize A String In C#

Let’s breakdown the individual parts of this code snippet.

The first line string sentence = "capitalize a string in csharp"; is declaring a string variable named sentence and assigning it the text “capitalize a string in csharp”.

The second line TextInfo myTI = new CultureInfo("en-US", false).TextInfo; is creating a TextInfo object that will then be used to capitalize the first letter of each word in the string. The “en-US” parameter is specifying that we want to use the English language rules as defined in the United States locale.

The third line sentence = myTI.ToTitleCase(sentence); capitalizes the first letter of each word in the sentence string using the ToTitleCase() method of the TextInfo object created in the previous step.

Final line Console.WriteLine(sentence); outputs the modified sentence string to the console. The result will be “Capitalize A String In Csharp”.

This method is case sensitive, meaning that it only alters uncapitalized words, if the sentence string was “capitalize A string in csharp;”, the output would be “Capitalize A String In Csharp;”, because ‘A’ is already capitalized, it stays the same.

c-sharp