views:

315

answers:

5

I have a java string with " " from a text file the program accesses with a Buffered Reader object. I have tried string.replaceAll(" ","") and it doesn't seem to work.

Any ideas?

cleaned = cleaned.replace(" "," ");
+2  A: 

The same way you mentioned:

String cleaned = s.replace(" "," ");

It works for me.

Manuel Selva
"Multiple exclamation marks ..." ;-)
Joachim Sauer
@Joachim - I think you mean "Multiple exclamation marks???" ... HTH :-)
Stephen C
@Stephen: I was reluctant to post the entire quote. [It's quite a topic](http://wiki.lspace.org/wiki/Multiple_exclamation_marks)
Joachim Sauer
Sorry Joachim I didn't see your comment because I tried to answer as quickest as possible to have more points than my colleague.On a side note I didn't get your comment ???
Manuel Selva
@Manuel: never mind me, just a little joke. Read the link in my previous comment, if you want to know more.
Joachim Sauer
@Joachim. I understand that I must be a little bit crazy with all the multiple exclamation marks I am using, isn't it ???
Manuel Selva
@Joachim - nice!!! (*Quickly takes underpants off head*).
Stephen C
A: 

Strings are immutable so You need to do

string = string.replaceAll(" ","")
Vash
He is already doing that: `cleaned = cleaned.replace(" "," ");`
jjnguy
Take back that -1; if you look at the `replaceAll` example posted in the original post, he's is not clearly already doing that.
Mark Peters
A: 

String.replace(char, char) takes char inputs (or CharSequence inputs)

String.replaceAll(String, String) takes String inputs

For example:

String origStr = "bat";
String newStr = str.replace.('a', 'i');
// Now:
// origStr = "bat"
// newStr = "bit"

The key point is that the return value contains the new edited String. The original String variable that invokes replace()/replaceAll() doesn't have its contents changed.

For example:

String origStr = "how are you?";
String newStr = origStr.replaceAll(" "," ");
String anotherStr = origStr.replaceAll(" ","");
// origStr = "how are you?"
// newStr = "how are you?"
// anotherStr = howareyou?"
JohnB
Note: `String implements CharSequence`.
BalusC
Note: there's a bug in S.O. that's now rendering my links at the bottom correctly.
JohnB
Links fixed; they had spaces that needed to be replaced with `%20`. Usually happens when you copy from your browser after it cleans up the URL to "look nice" instead of copying the raw URL.
Mark Peters
Thanks Mark, that's exactly how I was trying to make them look!
JohnB
A: 

the string in java are immutable... you have to do

String newStr = cleaned.replaceAll(" ", "");

This works correclty.

Maverick-F14
If you notice, the OP has the replaceAll value being put into a variable - overwriting the original value in the variable.
aperkins
NO HE DOESN'T! READ THE POST BEFORE DOWNVOTING.
Mark Peters
A: 

Why? It must be XML or HTML, i.e. a markup language, so why are you removing the author's markup?

EJP