Replace multiple space to one space in c#

Last Updated: 2022-11-27 22:35:18

Replace Multiple Space to One Space

If you want to know how to replace multiple spaces with one space this post is for you. In this post, I will show you how can you replace multiple spaces with one using regular expressions in C#. 
 

Example code for replacing multiple spaces to one using regular expressions in C#.

 

using System;
using System.Text.RegularExpressions;
public class SpaceReplace
{
   public static void Main(string[] args)
   {
       string sentence = @"This is a       string with         multiple spaces.";
       RegexOptions options = RegexOptions.None;
       Regex regex = new Regex("[ ]{2,}", options);     
       sentence = regex.Replace(sentence, " ");
       Console.WriteLine (sentence.Replace("\n", string.Empty));
   }
}

Note: Make use of your add System.Text.RegularExpressions to the top to use regular expressions.

Still you face problems, feel free to contact with me, I will try my best to help you.