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


There are several ways to replace multiple spaces with single space in C#.

String.Replace − Returns a new string in which all occurrences of a specified Unicode character or String in the current string are replaced with another specified Unicode character or String.

Replace(String, String, Boolean, CultureInfo)

String.Join Concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member.

Regex.Replace −In a specified input string, replaces strings that match a regular expression pattern with a specified replacement string.

Example using Regex

Example

 Live Demo

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 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 example Regex.Replace we have identified the additional spaces and replaced with single space

Example using string.Join

Example

 Live Demo

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 are splitting the text with multiple spaces using Split method and later join the splitted array using the Join method with single space.

Updated on: 19-Aug-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements