How to remove part of a line

Given the two lines, the base and delete, return the version of the base line where all instances of the delete line were deleted (not case sensitive). You can assume that the delete line has a length of 1 or more. Delete only non-overlapping instances, so with "xxx" deleting "xx" leaves "x".

withoutString("Hello there", "llo") โ†’ "He there"
withoutString("Hello there", "e") โ†’ "Hllo thr"
withoutString("Hello there", "x") โ†’ "Hello there"

Why I can not use this code:

public String withoutString(String base, String remove)
{
    base.replace(remove, "");
    return base;
}
+4
source share
5 answers

base.replacedoes not change the original instance String, since it Stringis an immutable class. Therefore, you must return the output replace, which is new String.

      public String withoutString(String base, String remove) 
      {
          return base.replace(remove,"");
      }
+8
source

String#replace() , , , . :

base = base.replace(remove, "")

+4

:

public String withoutString(String base, String remove) {
   //base.replace(remove,"");//<-- base is not updated, instead a new string is builded
   return base.replace(remove,"");
}
0

public String withoutString(String base, String remove) {
          return base.replace(remove,"");
      }

To enter:

base=Hello World   
remove=llo

Output:

He World

For more information on such operations, stringvisit this link.

0
source

The Apache Commons library has already implemented this method, you no longer need to write.

The code:

 return StringUtils.remove(base, remove);
0
source

All Articles