Follow @endyourif rss Facebook LinkedIn

C# String Extension to Split Camel Case C# String Extension to Split Camel Case

Published on Jun 9, 2022

I'm a big fan of extension methods as I have previously blogged about when it comes to C# Ordinal String Extension or C# Truncate String Extension to name a few examples.

This next extension is a nice little handy one when you want to convert a string that is CamelCased to a more readable string like Camel Cased.

I most often use this function when I have an Enum and I want to get a more human readable version without much effort.

Let's take a look at the code and it's usage:




using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace Common.Extensions
{
public static class StringExtensions
{
public static string SplitCamelCase(this string str)
{
return Regex.Replace(
Regex.Replace(
str,
@"(\P{Ll})(\P{Ll}\p{Ll})",
"$1 $2"
),
@"(\p{Ll})(\P{Ll})",
"$1 $2"
);
}
}
}


This can then be used as follows:


var myString = "ThisIsCamelCased";
Console.WriteLine(myString.SplitCamelCase());


This will output the string: This Is Camel Cased.

Tags: ASP.NET MVC and Web API Tutorial | c# | extension

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP