SUM
SUM

Reputation: 1661

Removing space from Java string doesn't work

String input = "c_Name == V-GE-DO50 OR c_Name == V-GE-DO-C";

I have tried

input.replaceAll(" ", "");
input.trim();

Both did not remove white space from the string

Want the string to look like c_Name==V-GE-DO50ORc_Name==V-GE-DO-C

Thanks

Upvotes: 0

Views: 3649

Answers (4)

Michal Rzemieniecki
Michal Rzemieniecki

Reputation: 161

String input = "c_Name == V-GE-DO50 OR c_Name == V-GE-DO-C";
input = input.replaceAll(" ", "");
System.out.println(input);

Result:

c_Name==V-GE-DO50ORc_Name==V-GE-DO-C

However, replaceAll takes Regular Expression as input value (for replacement) and this case covers getting rid of spaces in variable. So, if you want to simply get rid of spaces in your String, use input = input.replace(" ", "") to be more efficient.

Upvotes: 0

kosa
kosa

Reputation: 66677

Following works fine for me:

   String input = "c_Name == V-GE-DO50 OR c_Name == V-GE-DO-C";
   input = input.replaceAll(" ", "");
   System.out.println(input);

Output

c_Name==V-GE-DO50ORc_Name==V-GE-DO-C

Strings are immutable, I strongly suspect you are not assigning the string again after replaceAll (or) trim();

One more thing, trim doesn't remove spaces in middle, it just removes spaces at end.

Upvotes: 5

Brian Agnew
Brian Agnew

Reputation: 272437

Note that the String methods return a new String with the transformation applied. Strings are immutable - i.e. they can't be changed. So it's a common mistake to do:

input.trim();

and you should instead assign a variable:

String output = input.trim();

Upvotes: 9

chantheman
chantheman

Reputation: 5296

input.replaceAll("\s","") should do the trick

http://www.roseindia.net/java/string-examples/string-replaceall.shtml

Upvotes: 0

Related Questions