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

csharpserver side programmingprogramming更新于 2025/6/28 4:22:17

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

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

Replace(String, String, Boolean, CultureInfo)

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

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

使用正则表达式的示例 −

示例

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 方法将拆分后的数组与单个空格连接起来。


相关文章