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

王林
王林 转载
2023-09-18 08:53:02 896浏览

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

在 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 方法用单个空格连接分割后的数组。

以上就是如何在 C# 中将多个空格替换为单个空格?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除