Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove a part of a string

Tags:

java

string

Given two strings, base and remove, return a version of the base string where all instances of the remove string have been removed (not case sensitive). You may assume that the remove string is of length 1 or more. Remove only non-overlapping instances, so with "xxx" removing "xx" leaves "x".

withoutString("Hello there", "llo") → "He there"
withoutString("Hello there", "e") → "Hllo thr"
withoutString("Hello there", "x") → "Hello there"

Why can't I use this code:

public String withoutString(String base, String remove)
{
    base.replace(remove, "");
    return base;
}
like image 883
Sara Chatila Avatar asked Dec 04 '14 12:12

Sara Chatila


1 Answers

base.replace doesn't change the original String instance, since String is an immutable class. Therefore, you must return the output of replace, which is a new String.

      public String withoutString(String base, String remove) 
      {
          return base.replace(remove,"");
      }
like image 196
Eran Avatar answered Sep 19 '22 17:09

Eran