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
1
: 11046 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.

3
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");
		Console.WriteLine(newValue);
	}
}

Output:

This Is Test

You can check the fiddle here https://dotnetfiddle.net/4V0v70 but above Linq Solutions looks easy and simple to me.

1
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.

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






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

Full Name *

Email *




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