C# 如何用c语言中的特殊字符替换字符串中的多个空格#

C# 如何用c语言中的特殊字符替换字符串中的多个空格#,c#,replace,C#,Replace,如何用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,@"

如何用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
):

或者只有两个以上的空格(
[]
):


注意:
[\s\s]+
表示:在
[]
中指定的一个或多个字符组,因此当
\s
加倍时,它只表示:一个或多个空白字符。

尝试此正则表达式

[\s]{2,}
这在代码中是这样的:

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

您离正确的解决方案不远了。最简单的代码修复程序是:

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