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