Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace more than a space in a string with some special character in c#

Tags:

c#

replace

How to replace more than a space in a string with some special character in c#?

I have a string as

Hi I  am new  here. Would   you    please help    me?

I want output as

Hi I$am new$here. Would$you$please help$me?

I tried

string line=@"Hi I  am new  here. Would   you    please help    me?";
string line1 = Regex.Replace(line,@"[\s\s]+","$");
Console.WriteLine(line1);

but I am getting output as

Hi$I$am$new$here.$Would$you$please$help$me?

Could you please tell me where am I going wrong?

like image 625
Avinash More Avatar asked Dec 06 '13 21:12

Avinash More


People also ask

How string space replacement with character program work?

How string space replacement with character program work? This program will take a String as an input. Also program will take one character to replace with space. Now we will find the spaces available in the string using if check. And if space found then replace with given character.

How to replace spaces in a string with ch in Python?

Define a string. Determine the character 'ch' through which spaces need to be replaced. Use replace function to replace space with 'ch' character. String after replacing spaces with given character: Once-in-a-blue-moon String after replacing spaces with given character: Once-in-a-blue-moon

How to iterate a string in Java with space?

String is an array of character, so we can easily iterate the string using for loop and compare with the space. And if space found then replace with this index with the character given as an input by the user.

How to replace all matches in a string with a space?

The .Replace (temp, " ") replaces all matches in the string temp with a space. If you want to use this multiple times, here is a better option, as it creates the regex IL at compile time:


Video Answer


3 Answers

You should specify than you want more than two ({2,}) whitespace characters (\s):

string line1 = Regex.Replace(line,@"\s{2,}","$");

or only more than two spaces ([ ]):

string line1 = Regex.Replace(line,@"[ ]{2,}","$");

Note: [\s\s]+ means: one or more of character group specified in [], so as \s is doubled, it simply means: one or more of whitespace character.

like image 69
Konrad Kokosa Avatar answered Oct 20 '22 17:10

Konrad Kokosa


You were not far from the correct solution. The simplest fix for your code is:

string line1 = Regex.Replace(line,@"\s\s+","$");
like image 40
BartoszKP Avatar answered Oct 20 '22 16:10

BartoszKP


Try this regular expression

[\s]{2,}

which goes in the code as:

string line1 = Regex.Replace(line,@"[\s]{2,}","$");

Here is a rubular showing this

like image 42
Justin Pihony Avatar answered Oct 20 '22 16:10

Justin Pihony