tags:

views:

126

answers:

4

How to remove whitespaces between characters in c#?

Trim() can be used to remove the empty spaces at the beginning of the string as well as at the end. For example " C Sharp ".Trim() results "C Sharp".

But how to make the string into CSharp? We can remove the space using a for or a for each loop along with a temporary variable. But is there any built in method in C#(.Net framework 3.5) to do this like Trim()?

+12  A: 

You could use String.Replace method

string str = "C Sharp";
str = str.Replace(" ", "");

or if you want to remove all whitespace characters (space, tabs, line breaks...)

string str = "C Sharp";
str = Regex.Replace(str, "\s", "");
madgnome
oh .... yes . i for got of `replace` method. Thank you
Pramodh
That just replaces spaces, not whitespace (the two are not the same)
Paul
@Paul, you're right, thanks. I've updated my answer.
madgnome
A: 
string myString = "C Sharp".Replace(" ", "");
Andy Rose
Empty character literal '' produces a compiler error.
madgnome
replace `' '` into `" "`
Pramodh
+1  A: 

Use String.Replace to replace all white space with nothing.

eg

string newString = myString.Replace(" ", "");
w69rdy
That just replaces (ascii) space, not all whitespace? See discussion here http://msdn.microsoft.com/en-us/library/t97s7bs3.aspx
Paul
-1: You can't have an empty character literal.
Richard
@Paul Discussion where? That link is about String.Trim
w69rdy
@Richard Whoops forgot, have fixed this
w69rdy
@Pual I take your point, but his example suggests he simply means spaces, not whitespace in general
w69rdy
@w69rdy: ok, down vote removed... except SO is not seeing your edit (within 5min) but blocking my un-down vote :-( Now with your edit I can remove it.
Richard
@w69rdy - read further down about the characters Trim removes. The OP seemed to me to want the equivalent of Trim for all whitespace.
Paul
@Paul I disagree, he only compares it to Trim in terms of functionality, not specifics. His example suggests he's only interested in spaces and he never mentions anything about other forms of whitespace. If he was I would have thought he would of made that a lot clearer
w69rdy
OK, let's wait for the OP to clarify :) I didn't downvote you, anyway :-P
Paul
lol ok no worries. It looks like he's got his answer anyway! ;)
w69rdy
A: 

Not a built in method, but pretty simple

Paul