Niminim Niminim - 2 months ago 5x
Java Question

Java - using replaceAll without getting a space

I have a problem using replace all, it add a space instead of the replaced words. A simple example:

String str= "I like java";

gives "I like(a space here)"

String str= "I like java";

gives "I(2 spaces here)java"

String str= "I like java";

gives "(2 spaces here)like java"

How can I truncate this space just by using replaceAll ? Iguess it has something to do with the replacing argument(""), right ?

Note: I have a few words that should be deleted if found in a string, and I don't know where they'll be found.



You're replacing "java" with "", leaving the two spaces you originally had in your string, rather than replacing " java" (note the space). But, this would work...

String str= "I like java"; 
str = str.replaceAll(" java","");

If you're looking to replace only one of the spaces around that word, with a preference for the first space, you might do this...

String regex = " like|like ";
System.out.println("I like java".replaceAll(regex,""));
System.out.println("like java".replaceAll(regex,""));