Home  >  Article  >  Backend Development  >  How to replace multiple spaces with a single space in C#?

How to replace multiple spaces with a single space in C#?

王林
王林forward
2023-09-18 08:53:021545browse

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

In C#, there are several ways to replace multiple spaces with a single space.

String.Replace - Returns a new string in which all occurrences of the specified Unicode character or string replace the contents of the current string with another specified Unicode character or string .

Replace(String, String, Boolean, CultureInfo)

String.Join Connect the elements of the specified array or members of the collection, using between each element or member The specified delimiter.

Regex.Replace - In the specified input string, replaces the matched string with the regular expression pattern of the specified replacement string.

Example using regular expressions -

Example

Real-time demonstration

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();
      }
   }
}

Output

The above program The output of is

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

In the above example Regex.Replace we have identified the extra spaces and Replace with a single space

Example using string.Join -

Example

Real-time demonstration

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();
      }
   }
}

Output

The output of the above program is

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

In the above, we use the Split method to split the text into multiple spaces, Later use the Join method to join the split arrays with a single space.

The above is the detailed content of How to replace multiple spaces with a single space in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete