How to Add Spaces before Capital letter in a string using C#?

In my MVC project, I am getting dropdown text data as "NoEffect", "FadeOut" etc, now I would like to show user as "No Effect", "Fade out" etc, show how can I achieve it using C#?

Any method would work, using regex or without using regex.

Asked by:- manish
: 10715 At:- 9/7/2018 12:08:44 PM
C# string put space before capital char

3 Answers
profileImage Answered by:- jaya

Try using this below Linq code(without using regex) to add space before capital letters

var YourString= "NoEffect";

//get output as "No Effect"
@string.Concat(YourString.Select(x => Char.IsUpper(x) ? " " + x : x.ToString())).TrimStart(' ');

This should work.

At:- 9/7/2018 3:29:29 PM
This looks easier than using regex, not sure about performance though 0
By : manish - at :- 9/9/2018 5:50:47 PM

profileImage Answered by:- neena

Here is the simple program to add space before capital letters using regex in C#

using System;
using System.Text.RegularExpressions;
public class Program
	public static void Main()
		var oldvalue= "ThisIsTest";
		var newValue = Regex.Replace(oldvalue, "([a-z])([A-Z])", "$1 $2");


This Is Test

You can check the fiddle here but above Linq Solutions looks easy and simple to me.

At:- 9/10/2018 11:39:46 AM

profileImage Answered by:- pika

If you want to create Extension method to add space before capital 

public static class Extensions
    public static string SpaceBeforeCapital( this string Input )
        return new string(Input.SelectMany((c, i) => i > 0 && char.IsUpper(c) ? new[] { ' ', c } : new[] { c }).ToArray());

Now you can use it like MyCasedString.SpaceBeforeCapital() this.

At:- 6/3/2022 10:46:32 AM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use