Reputation: 99
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?
Upvotes: 5
Views: 200
Reputation: 16878
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.
Upvotes: 6
Reputation: 35891
You were not far from the correct solution. The simplest fix for your code is:
string line1 = Regex.Replace(line,@"\s\s+","$");
Upvotes: 2
Reputation: 67075
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
Upvotes: 1