【问题标题】:remove two or more empty between space in word删除word中空格之间的两个或多个空格
【发布时间】:2014-11-10 13:31:09
【问题描述】:

我想用C# 中的破折号替换单词中的任何空格。但我的问题是当我想像这样删除示例字符串中的空格时:

"a  b"

"a    b"

当我尝试这个时,我得到了这个结果:

"a--b""a---b"

如何在单词之间添加一个破折号?

像这样:

"a b"

"a-b"

【问题讨论】:

  • 你做得怎么样?你的代码是什么? string.Replace...?

标签: c# asp.net regex


【解决方案1】:

你可以像下面这样使用

string xyz = "1   2   3   4   5";
xyz = string.Join( "-", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));

参考

  1. How do I replace multiple spaces with a single space in C#?
  2. How to replace multiple white spaces with one white space

【讨论】:

    【解决方案2】:

    您可以在这里简单地使用Regex.Replace

    Regex.Replace("a    b", @"\s+", "-");
    

    \s 会查找 space,如果按顺序找到一个或多个空格,则 + 会计算空格。模式将被匹配和替换。

    【讨论】:

      【解决方案3】:

      这可以通过多种方法来完成。使用正则表达式:

          string a = "a         b   c de";
          string b = Regex.Replace(a, "\\s+", "-");             
      

      或者如果你不想使用正则表达式,这里有一个函数,它将一个字符串和要替换的字符作为参数并返回格式化的字符串。

          public string ReplaceWhitespaceWithChar(string input,char ch)
          {
              string temp = string.Empty;
              for (int i = 0; i < input.Length; i++)
              {
      
                  if (input[i] != ' ')
                  {
                      temp += input[i];
                  }
                  else if (input[i] == ' ' && input[i + 1] != ' ')
                  {
                      temp += ch;
                  }
              }
              return temp;
          }        
      

      【讨论】:

        【解决方案4】:

        您可以根据需要使用此代码

                string tags = "This           sample";
                string cleanedString = System.Text.RegularExpressions.Regex.Replace(tags, @"\s+", "-");
        
                Response.Write(cleanedString);
        

        结果将是:

        "This-sample"
        

        我希望它对你有用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-12-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-25
          • 2012-03-13
          • 2015-06-08
          • 2014-07-30
          相关资源
          最近更新 更多