如何在C#中将多个空格替换为单个空格?


在C#中,有多种方法可以将多个空格替换为单个空格。

String.Replace − 返回一个新的字符串,其中当前字符串中所有指定的Unicode字符或字符串都被替换为另一个指定的Unicode字符或字符串。

Replace(String, String, Boolean, CultureInfo)

String.Join 使用指定的每个元素或成员之间的分隔符,连接指定数组的元素或集合的成员。

Regex.Replace − 在指定的输入字符串中,用指定的替换字符串替换与正则表达式模式匹配的字符串。

使用Regex的示例

示例

 在线演示

using System;
using System.Text.RegularExpressions;
namespace DemoApplication{
   class Program{
      public static void Main(){
         string stringWithMulipleSpaces = "Hello World. Hi Everyone";
         Console.WriteLine($"String with multiples spaces:
            {stringWithMulipleSpaces}");
         string stringWithSingleSpace = Regex.Replace(stringWithMulipleSpaces, @"\s+", " ");
         Console.WriteLine($"String with single space: {stringWithSingleSpace}");
         Console.ReadLine();
      }
   }
}

输出

以上程序的输出为

String with multiples spaces: Hello World. Hi Everyone
String with single space: Hello World. Hi Everyone

在上面的示例中,Regex.Replace识别了多余的空格并将其替换为单个空格。

使用string.Join的示例

示例

 在线演示

using System;
namespace DemoApplication{
   class Program{
      public static void Main(){
         string stringWithMulipleSpaces = "Hello World. Hi Everyone";
         Console.WriteLine($"String with multiples spaces:
         {stringWithMulipleSpaces}");
         string stringWithSingleSpace = string.Join(" ",
         stringWithMulipleSpaces.Split(new char[] { ' ' },
         StringSplitOptions.RemoveEmptyEntries));
         Console.WriteLine($"String with single space: {stringWithSingleSpace}");
         Console.ReadLine();
      }
   }
}

输出

以上程序的输出为

String with multiples spaces: Hello World. Hi Everyone
String with single space: Hello World. Hi Everyone

在上面,我们使用Split方法分割包含多个空格的文本,然后使用Join方法将分割后的数组用单个空格连接起来。

更新于:2020年8月19日

3K+浏览量

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.