Convert string to Title and Camel Case in C#


While working with strings two of the most common requirements are to convert string to title and camel case .We can use inbuilt and custom methods in c# for these tasks.

We will see how to convert string to Title and Camel Case in C#.

Following are two of the methods for converting string:

Convert String to TitleCase

Sometimes we have the requirement while working with textual data to convert the text into camel case.If we just want to convert every word in the text to camel case then we can use the ToTitleCase method.The ToTitleCase(string) is a method defined in the TextInfo class of the System.Globalization namespace.

To convert the string to title case we just pass the string to the ToTitleCase(string) method.Below we are passing some string value to this method

staticvoidMain(string[]args){stringtext="This is a sample text";stringcamelCaseText=System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text);Console.WriteLine(camelCaseText);Console.ReadLine();}

On executing the above codewe get the following output

Convert String to CamelCase

Though we can use the ToTitleCase(string) method for converting a string to a title case but when working with a paragraph we need to convert the first wordof a sentence to title case.For this we can use the following code.

classProgram{//Create a new delegate typepublicdelegatestringFormatString(stringrawString);staticvoidMain(string[]args){stringstrParagraph="first sentence.second sentence";FormatString format=RemoveSpace;stringformatted=RemoveSpace(strParagraph);FormatString split=Split;varfinalString=Split(formatted); Console.WriteLine(finalString);Console.ReadLine();} publicstaticstringRemoveSpace(stringfullString){returnfullString.Trim(); } publicstaticstringSplit(stringfullString){varstrArr=fullString.Split(newchar[]{'.'});varnewStrArr=strArr;foreach(variteminstrArr)for(intiCount=0;iCount<strArr.Count();iCount++){strArr[iCount]=strArr[iCount].Insert(0,strArr[iCount][0].ToString().ToUpper());strArr[iCount]=strArr[iCount].Remove(1,1);}returnstring.Join(".",strArr);}}

In the aboveexample a delegate type FormatString is declared as:


The method RemoveSpace is assigned to delegate FormatString and is called.

FormatString format=RemoveSpace;stringformatted=RemoveSpace(strParagraph);

the result of the first method call is passed to the second second delegate instance.The second instance refers to the Split method.

FormatString split=Split;varfinalString=Split(formatted);

In the Split(string) method the passed argument is split based on the “.” separator.


Finally we loop over the array and convert the first word to title case.


we get the following output on executing the above example