卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64334本站已运行4115

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

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

卓越飞翔博客
上一篇: 利用Golang开发微服务可以满足哪些实际需求?
下一篇: Golang微服务开发能实现哪些功能?
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏