0

I want to remove all white spaces from string variable which contains a sentence. Here is my code:

string s = "This text contains white spaces";
string ns = s.Trim();

Variable "sn" should look like "Thistextcontainswhitespaces", but it doesn't(method s.Trim() isn't working). What am I missing or doing wrong?

Kalvis
  • 595
  • 2
  • 7
  • 13
  • What language is this? – Emmet Mar 14 '14 at 20:30
  • what is the language? – Steven Martin Mar 14 '14 at 20:30
  • I'm using c# language – Kalvis Mar 14 '14 at 20:31
  • The Trim method removes from the current string all leading and trailing white-space characters. Leading white-space characters are whitespace characters which occur before all characters in the string that are not whitespace. Trailing white-space characters are whitespace characters which occur after all characters in the string that are not whitespace. Calling Trim() on the string " this is " would return "this is". – George Tomlinson Mar 14 '14 at 20:39
  • Check this link as well `http://stackoverflow.com/questions/5203607/fastest-way-to-remove-white-spaces-in-string` – Sourav 'Abhi' Mitra Mar 17 '14 at 17:04

2 Answers2

4

The method Trim usually just removes whitespace from the begin and end of a string.

string s = "     String surrounded with whitespace     ";
string ns = s.Trim();

Will create this string: "String surrounded with whitespace"

To remove all spaces from a string use the Replace method:

string s = "This text contains white spaces";
string ns = s.Replace(" ", "");

This will create this string: "Thistextcontainswhitespaces"

Flovdis
  • 2,945
  • 26
  • 49
2

Try this.

s= s.Replace(" ", String.Empty);

Or using Regex

s= Regex.Replace(s, @"\s+", String.Empty);
thepirat000
  • 12,362
  • 4
  • 46
  • 72
Arjit
  • 3,290
  • 1
  • 17
  • 18
  • I recommend `String.Replace` if you know the whitespace will always be a space character (ASCII 32). Regular expressions have much more overhead. – NathanAldenSr Mar 14 '14 at 20:38