In previous article I have mentioned how to Remove all whitespace from string in SQL Server but now in this article, I have provided working example with output to show how we can remove all whitespace from string in C# or you can how to trim all whitespace in between text in C#.

Remove Whitespace from string using Replace Method

In this example, we will remove whitespace from string using string.Replace Method of C#.

Here is the example of sample code considering console application

using System;
					
public class Program
{
	public static void Main()
	{
		string str = "Hello World This Is Test";
        str = str.Replace(" ", String.Empty);
		Console.WriteLine(str);
	}
}

Output:

remove-whitespace-from-string-csharp

Remove Whitespace from string using Regex method

This method is slower because of Regex, but we can still use it in some cases, so here is the working example for it

using System;
using System.Text.RegularExpressions;
					
public class Program
{
	static Regex whitespace = new Regex(@"\s+", RegexOptions.Compiled);

	public static string TrimAllWithRegex(string str) {
		return whitespace.Replace(str, "");
	}
	public static void Main()
	{
		
		string str = "Hello World This Is Test";        
		Console.WriteLine(TrimAllWithRegex(str));
	}	
}

Output:

HelloWorldThisIsTest

Remove whitespace from string using Inplace Char Array Method

This is the fastest method of all for removing whitespace. Basically, we wil convert the input string into a char array, first and then scans the string for removing whitespace characters inplace (without creating intermediate buffers or strings).

So we will create 2 helper methods for it, first

public static bool isWhiteSpace(char ch) {
        // this is surprisingly faster 
		switch (ch) {
			case '\u0009': case '\u000A': case '\u000B': case '\u000C': case '\u000D':
			case '\u0020': case '\u0085': case '\u00A0': case '\u1680': case '\u2000':
			case '\u2001': case '\u2002': case '\u2003': case '\u2004': case '\u2005':
			case '\u2006': case '\u2007': case '\u2008': case '\u2009': case '\u200A':
			case '\u2028': case '\u2029': case '\u202F': case '\u205F': case '\u3000':
				return true;
			default:
				return false;
		}
	}
	public static string TrimAllWithInplaceCharArray(string str) {
		var len = str.Length;
		var src = str.ToCharArray();
		int dstIdx = 0;
		for (int i = 0; i < len; i++) {
			var ch = src[i];
			if (!isWhiteSpace(ch))
				src[dstIdx++] = ch;
		}
		return new string(src, 0, dstIdx);
	}

and then we will use it in our main method, so here is the complete example using above C# code

using System;
					
public class Program
{
	public static bool isWhiteSpace(char ch) {
        // this is surprisingly faster 
		switch (ch) {
			case '\u0009': case '\u000A': case '\u000B': case '\u000C': case '\u000D':
			case '\u0020': case '\u0085': case '\u00A0': case '\u1680': case '\u2000':
			case '\u2001': case '\u2002': case '\u2003': case '\u2004': case '\u2005':
			case '\u2006': case '\u2007': case '\u2008': case '\u2009': case '\u200A':
			case '\u2028': case '\u2029': case '\u202F': case '\u205F': case '\u3000':
				return true;
			default:
				return false;
		}
	}
	public static string TrimAllWithInplaceCharArray(string str) {
		var len = str.Length;
		var src = str.ToCharArray();
		int dstIdx = 0;
		for (int i = 0; i < len; i++) {
			var ch = src[i];
			if (!isWhiteSpace(ch))
				src[dstIdx++] = ch;
		}
		return new string(src, 0, dstIdx);
	}
	
	
	public static void Main()
	{
		
		string str = "Hello World This Is Test";        
		Console.WriteLine(TrimAllWithInplaceCharArray(str));
	}
}

Output:

HelloWorldThisIsTest

Replace multiple spaces in a string with a single space

Suppose, you have a string, in which in-between words there are lots of spaces, like in this  example: "Hello   World   This Is   Test" and then you want to keep only a single space in between words, to make it "Hello World This Is Test", then you can do it using Regex and Replace Method in C# as shown below in console application example

using System;
using System.Text.RegularExpressions;
					
public class Program
{		
	public static void Main()
	{	
		string str = "Hello     World    This    Is   Test";
        string newStrstr = Regex.Replace(str, " {2,}", " ");
		Console.WriteLine(newStrstr);
	}
}

That's it, I hope it helps.

You may also like to read:

How to get file extension or file size in C# ? ( Code With Example )

Read file in C# (Text file .NET and .NET Core example)

Create Web-API in Visual Studio 2022 Step by Step

How to read pdf file in C#? (Working example using iTextSharp)