Non-Existent Non-Existent - 3 months ago 11
Java Question

Deleting A Specified Substring in Java

This is actually an exercise from CodingBat. The definition of the problem is as follows:


Given a string, if the string "del" appears starting at index 1, return a string where that "del" has been deleted. Otherwise, return the string unchanged.


  • delDel("adelbc") → "abc"

  • delDel("adelHello") → "aHello"

  • delDel("adedbc") → "adedbc"




My work is as follows:

public String delDel(String str) {
String del = "del";

if (str.indexOf(del, 1) == 1){
str.replaceFirst("del", null);
}

return str;
}


It works fine for most of the cases, but I get NullPointerException in "adelbc", "adelHello" and "adel" cases. I can't quite understand why.

Answer

If you look closely in the OpenJDK sources, you'll note that replaceFirst delegates work to the regexp functions, including this one for replacing step:

public String replaceFirst(String replacement) {
    if (replacement == null)
        throw new NullPointerException("replacement");
    reset();
    if (!find())
        return text.toString();
    StringBuffer sb = new StringBuffer();
    appendReplacement(sb, replacement);
    appendTail(sb);
    return sb.toString();
}

Note that replacement can not be null. I assume the behaviour is going to be similar in other implementations of the JRE. Please use "" - empty string - instead of null as the replacement.

Also as mentioned in the comments by cricket_007 you want to save the result of replaceFirst for returning, since the original string will not be affected (all Strings in Java are immutable). The final piece of code:

public String delDel(String str) {
  String del = "del";

  if (str.indexOf(del, 1) == 1){
    return str.replaceFirst("del", "");
  }

  return str;
}
Comments