• 01 Feb 2023
  • C#

Replace and Lowercase a String in C Sharp

Replacing and lowercasing a string are common operations and can be useful for a variety of reasons. Primary among them would be to normalize your URL slug, making it user friendly. i.e in the case your blog title is 'This is a Good Blog Post', for readability and to positively affect your SEO you would want it displayed as 'this-is-a-good-blog-post'.

It could also be of some use in Natural Language Processing.

This is how we do it in C#.

 


public string ReplaceAndLowercase(string phrase)
{
   char[] charactersToReplace = { ',', '_', '/', '.',':',';' };
   string result = phrase.ToLower();
   for (int i = 0; i < charactersToReplace.Length; i++)
   {
     result = result.Replace(charactersToReplace[i], '-');
   }
   return result.Replace(' ', '-').ToLower();
}

 

And voila! you can call this method to replace and lowercase your string.

 

 

 

Share: