
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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.