Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

practice: removing all string occurrences from another

Tags:

java

I'm doing some beginner's coding practice and I ran into this problem: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).

This is what I have so far, but it's not working at all.

public String withoutString(String base, String remove) {

 for (int i=0; i<base.length()-remove.length(); i++){
  if (base.substring(i, i+remove.length()).equals(remove)){
  base = base.substring(i, base.indexOf("remove")-1) + base.substring(base.indexOf("remove"), base.length()-remove.length());
    }
  }
  return base;
}

I've yet to deal with the case sensitive part to make it more visible for myself. I'm also not sure why I can't use base.replaceAll("remove",""); Any help is appreciated.

EDIT*: I made a rookie mistake and the replaceAll still works. Additionally, how could I have done this using loops and conditionals? Would it have been messy like what I had previously?

like image 383
xheyhenry Avatar asked Sep 19 '13 23:09

xheyhenry


2 Answers

You can use

String result = base.replaceAll(remove,"");

With quotes as you where trying it is actually trying to remove the string "remove".

To deal with the case insenstive you can use the regex flag for ignore case (?i) in the front so then you can call

String result = base.replaceAll("(?i)" + remove,"");

This does mean that the String remove, is now a regular expression now so special characters may have undesired results. For example if your remove string was ., you would end up with every character removed. If you don't want it as a regex then use

String result =  Pattern.compile(remove, Pattern.LITERAL).matcher(base).replaceAll("")

Which can also include the case insensitive flag like so as they are a bitmask, see Pattern for more

Pattern.LITERAL | Pattern.CASE_INSENSITIVE

EDIT

To do it using your loop, just do this loop

for (int i=0; i <= base.length()-remove.length(); i++)
{
    if (base.substring(i, i+remove.length()).equals(remove))
    {  
        base = base.substring(0, i) + base.substring(i + remove.length() , base.length());
        i--;
    }
}
like image 167
Java Devil Avatar answered Oct 13 '22 01:10

Java Devil


indexOf("remove") means, you are searching for the (fixed) STRING remove, not for the value of the String named remove - which is most likey not, what you want to do. Same applies for your replaceAll("remove") attempt.

remove the " so you are using the VALUE of the String named remove, not the fixed string "remove"

Example:

String remove = "test";
System.out.println(remove) // will print: test
System.out.println("remove") // will print: remove
like image 22
dognose Avatar answered Oct 12 '22 23:10

dognose