Practice: deleting all rows from another

I practice beginner coding, and I ran into this problem: given the two lines, base and delete, return the version of the base line where all instances of the delete line were deleted. (not case sensitive).

This is what I have so far, but it does not work 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 still need to deal with the case-sensitive part to make it more visible to me. I am also not sure why I cannot use base.replaceAll ("remove", ""); Any help is appreciated.

EDIT *: I made a rookie mistake and replaceAll still works. Also, how could I do this using loops and conventions? Would it be dirty, like what I had before?

+7
java
source share
4 answers

you can use

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

With the quotation marks where you are trying, it actually tries to remove the "remove" .

To deal with the insenstive case, you can use the regex flag for the case of ignoring (?i) in front, after which you can call

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

This means that String remove is now a regular expression, so special characters can have unwanted results. For example, if your line for deletion was . , you had to delete each character. If you do not want this to be like a regular expression, use

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

Which may also include case insensitive flags, as they are a bitmask, see Pattern for more.

 Pattern.LITERAL | Pattern.CASE_INSENSITIVE 

EDIT

To do this 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--; } } 
+8
source share

indexOf("remove") means that you are looking for a (fixed) STRING remove , not a String value called remove , which is most likely what you want to do. The same applies to your attempt to replaceAll("remove") .

remove " to use the VALUE value of the string named remove , rather than the fixed string "remove"

Example:

 String remove = "test"; System.out.println(remove) // will print: test System.out.println("remove") // will print: remove 
+1
source share

You should use the flag (?i) or:

 base = Pattern.compile(remove, Pattern.CASE_INSENSITIVE).matcher(base).replaceAll(""); 
0
source share

Try the following:

 if(base.indexOf(remove) != -1){ base.replaceAll(remove,""); } 
0
source share

All Articles