0

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

1
  • 10
    Strings in Java are immutable. You have to assign like this: String result = input.replaceAll(" ", ""); Commented Aug 20, 2012 at 19:03

4 Answers 4

9

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. That helped. Seeing the answers below wonder why it works for some.
5

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.

Comments

0

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

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

Comments

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

1 Comment

Indeed, that's the output. OP needs to use that String for any reason, and your answer doesn't provide using the result at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.