如何用c#中的一些特殊字符替换字符串中的多个空格?
我有一个字符串作为
Hi I am new here. Would you please help me?
我想要输出为
Hi I$am new$here. Would$you$please help$me?
我试过了
string line=@"Hi I am new here. Would you please help me?";
string line1 = Regex.Replace(line,@"[\s\s]+","$");
Console.WriteLine(line1);
但是我得到的输出是
Hi$I$am$new$here.$Would$you$please$help$me?
你能告诉我哪里错了吗?
最佳答案
您应该指定超过两个 ({2,}
) 个空白字符 (\s
):
string line1 = Regex.Replace(line,@"\s{2,}","$");
或者只有两个以上的空格([ ]
):
string line1 = Regex.Replace(line,@"[ ]{2,}","$");
注意:[\s\s]+
表示:[]
中指定的一个或多个字符组,如\s
加倍,它只是表示:一个或多个空白字符。
关于c# - 如何用c#中的一些特殊字符替换字符串中的多个空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20433770/