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?
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.
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
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.
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:
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.
You were not far from the correct solution. The simplest fix for your code is:
string line1 = Regex.Replace(line,@"\s\s+","$");
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With