Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations sizbut on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Removing Spaces

Status
Not open for further replies.

hbutt

Programmer
Apr 15, 2003
35
GB
hi there,
jus wanted to know is there a way of removing spaces from a string.

thanx
hgsb
 
if you would remove all spaces:
yourString.replaceAll(" ", "");

if you would remove only beginning and ending spaces:

str = yourString.trim();

Ion Filipski
1c.bmp

ICQ: 95034075
AIM: IonFilipski
filipski@excite.com
 
the replaceAll statement dont work.
 
The replaceAll statement does work, try the following example.

public final class RemoveSpaces {
public static void main(String[] argv) {
String s = "TEST SPACE A B CCC D";
System.out.println(s + " " + s.replaceAll(" ", ""));
}
}
 
the replaceAll statement dont work.

It's a common mistake to forget, that Strings are final in Java.

If you say:

String s = "A great example";
s.replaceAll (" ", "#");

S.o.p (s);

s in still the same.
If you have read the documentation carefully, you would have seen, that s.replaceAll (a,b) RETURNS a String, in which all a are replaced with b.
It doesn't affect s itself.
But if you assign that result to s again:

s = s.replaceAll (a, b);
S.o.p (s);

you will get the intendet result.

'replaceAll statement dont work' is a kind of 'select is broken'-Pattern, see: pragmatic programmer, d.thomas, a.hunt.

 
>stefanwagner
>the replaceAll statement dont work.
Function replaceAll works and it returns a string what you need. And it is the right function to use in this case. How to use this function is written in a lot of manuals, so I've shown only the right direction.

If someone point you with the finger to the moon and you look at the finger, you will not see the moon.

Ion Filipski
1c.bmp

ICQ: 95034075
AIM: IonFilipski
filipski@excite.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top