Replace white space with null

  • Thread starter Thread starter ad
  • Start date Start date
A

ad

I want to remove all space in a string;
I use :

sMyString="a b c";

sMyString=sMyString.Replace(' ',null);

But it fail when compiling.

How can I do that?
 
Tobin Harris said:
mystring = mystring.Replace(' ', '');

That won't work, as '' isn't a character. In this case, the OP wants (I
believe) to replace the existence of a character with *no* character at
all - so you need to use strings instead. See Chad's reply for how to
do it.
 
In addition to Jon's and Chad's replies, rather that using the double quotes
to represent an empty string, it would be better practice to use
string.Empty as thus...

newString = originalString.Replace(" ", string.Empty);

There is no real difference between the two methods Except readability of
code (and potential for accidental typos -i.e. spaces between quotes).

Br,

Mark.
 
Mark Broadbent said:
newString = originalString.Replace(" ", string.Empty);

There is no real difference between the two methods Except readability
of code (and potential for accidental typos -i.e. spaces between
quotes).

I think its is strongly a matter of personal preference, both are certainly fine. Most of use have
been using "" for 10, or even 20 years as an empty string. I can see your point that it could be goofed
up, but to be honest I have never ever had a bug because of this. "" is pretty easy to spot.


--
Chad Z. Hower (a.k.a. Kudzu) - http://www.hower.org/Kudzu/
"Programming is an art form that fights back"

Make your ASP.NET applications run faster
http://www.atozed.com/IntraWeb/
 
Chad Z. Hower aka Kudzu said:
I think its is strongly a matter of personal preference, both are
certainly fine. Most of use have been using "" for 10, or even 20
years as an empty string. I can see your point that it could be
goofed up, but to be honest I have never ever had a bug because of
this. "" is pretty easy to spot.

Likewise - I'm definitely a fan of "" over String.Empty.
 
ad said:
I want to remove all space in a string;
I use :

sMyString="a b c";

sMyString=sMyString.Replace(' ',null);

But it fail when compiling.

How can I do that?
use
sMyString=sMyString.Replace(" ","");
 
Back
Top