Formating the string to Title Case in c#


The following code snippet formats the string in such a way that every letter of the word in a sentence is capital instead of the whole word in a sentence to be in upper case or lower case. The situation can arise if for eg the whole address of the customer is shown in upper case or in lower case in that case we will need to format the string to title case

Following is the code snippet to format the string to Title Case.

str is the string that needs to be formatted.


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

for (int i = 0; i <= words.Length - 1; i++)
{
if ((!object.ReferenceEquals(words[i], string.Empty)))
{
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);
}


String.Join allows you to easily divide parts of an output string with commas or other delimiters.

Here I'm seperating the string with space and then returning the string else if not done in this way then the array of words will be seen without any seperation.

One more approach is as follows


public string ToTitleCase(string str)
{
string strFormat = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str().ToLower());
return strFormat;

}



For CultureInfo class you need to add namespace
using System.Globalization


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: