5

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;
}
1
  • 7
    I didn't get, why people up voting this question.. :P Commented Dec 4, 2014 at 12:37

5 Answers 5

8

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

Comments

4

String#replace() returns a new string, doesn't change the one it is invoked on, since strings are immutable. Use this in your code:

base = base.replace(remove, "")

Comments

0

Update your code:

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

Comments

0

Try following code

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

For Input :

base=Hello World   
remove=llo

Output :

He World

For more on such string operations visit this link.

Comments

0

Apache Commons library has already implemented this method,you don't need to write again.

Code :

 return StringUtils.remove(base, remove);

Comments

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.