Replace white space with null

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?
 
J

Jon Skeet [C# MVP]

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.
 
M

Mark Broadbent

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.
 
M

Michael S

A bit overkill, but I like it.
I'll code using String.Empty from now on.

- Michael S
 
C

Chad Z. Hower aka Kudzu

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/
 
J

Jon Skeet [C# MVP]

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.
 
?

=?ISO-8859-1?Q?Andr=E9?=

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(" ","");
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top