Remove spaces from a string C# VB.Net

How do I replace multiple spaces with a single space in C# vb.net asp.net

A string is a sequential collection of Unicode characters that is used to represent text. String objects are immutable that is they cannot be changed after they have been created. This chapter will explain how to remove spaces, newline, tab, carriage return, digits etc from a string.

C#

string str = "This is a test";
str = str.Replace(" ", String.Empty);
MessageBox.Show(str);

VB.Net

Dim str As String = "This is a test"
str = str.Replace(" ", [String].Empty)
MessageBox.Show(str)

String.Empty - Represents the empty string

Output:

Thisisatest

How to remove spaces inside a string

C#

string str = "This is a test";
str = str.Replace(" ", "");
MessageBox.Show(str);

VB.Net

Dim str As String = "This is a test"
str = str.Replace(" ", "")
MessageBox.Show(str)

Output:

Thisisatest

Remove all spaces in a string using Regex

using System.Text.RegularExpressions;

C#

string str = "This is a test";
str = Regex.Replace(str, @"\s", "");
MessageBox.Show(str);

VB.Net

Dim str As String = "This is a test"
str = Regex.Replace(str, "\s", "")
MessageBox.Show(str)

Output:

Thisisatest

Replace multiple spaces in a string to single space

C#

string oldStr = "This      is      a      test";
string newStrstr = Regex.Replace(oldStr, " {2,}", " ");
MessageBox.Show(oldStr + "  ,  " + newStrstr);

VB.Net

Dim oldStr As String = "This      is      a      test"
Dim newStrstr As String = Regex.Replace(oldStr, " {2,}", " ")
MessageBox.Show(oldStr & "  ,  " & newStrstr)

Output:

This is a test

String Trim() methods

Trim eliminates leading and trailing whitespace.

C#

string oldStr = "    *This is a test*  ";
string newStr = oldStr.Trim();
MessageBox.Show("(" + oldStr + ")" + "(" + newStr + ")");

VB.Net

Dim oldStr As String = "    *This is a test*  "
Dim newStr As String = oldStr.Trim()
MessageBox.Show("(" & oldStr & ")" & "(" & newStr & ")")

Output

(  *This is a test*  )  (*This is a test*)

String TrimStart() method

trim spaces in a string C# vb.net asp.nets

Removes all leading occurrences of a set of characters specified in an array from the current String object.

C#

string str = "    *This is a test*  ";
str = str.TrimStart();
MessageBox.Show("(" + str + ")");

VB.Net

Dim str As String = "    *This is a test*  "
str = str.TrimStart()
MessageBox.Show("(" & str & ")")

Output:

(*This is a test*  )

String TrimEnd() method

trim blank spaces in a string C# vb.net asp.nets

Removes all trailing occurrences of a set of characters specified in an array from the current String object.

C#

string str = "    *This is a test*  ";
str = str.TrimEnd();
MessageBox.Show("(" + str + ")");

VB.Net

Dim str As String = "    *This is a test*  "
str = str.TrimEnd()
MessageBox.Show("(" & str & ")")

Output

(  *This is a test*)


NEXT.....Remove new line from a string