Home > Software design >  Deleting del word from input in Java
Deleting del word from input in Java

Time:11-22

Question
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.
My Code

public String delDel(String str) {
  return str.replaceAll("del","");
}

but my code failed for some test cases like:
1)delDel("del") → "del" ""
2)delDel("aadelbb") → "aadelbb" "aabb"

I am beginner to Java. Can anyone tell me why it's showing that error.
Question link : Image of problem

CodePudding user response:

Here String::replaceFirst should be used with a simpler regexp "^(.)del" because only the first occurrence at the beginning of the string needs to be matched:

public String delDel(String str) {
  return str.replaceFirst("^(.)del", "$1");
}

Another solution may use String::regionMatches (or even shorter String::startsWith) and String::charAt String::substring to perform the task without regular expressions at all:

public String delDel(String str) {
    return str.startsWith("del", 1) ? str.charAt(0)   str.substring(4) : str;
//  return str.regionMatches(1, "del", 0, 3) ? str.charAt(0)   str.substring(4) : str;
}

CodePudding user response:

This will do

public String delDel(String str) {
  return str.replaceAll("^(.{1})del","$1");
}

Explanation:

i search

  • ^ : starting at the begining of the string

  • (.{1}): i expect any character "." once "{1}" and i select it "()"

  • del: then it must match "del"

then i replace with:

  • $1 : the content previously selected "(.{1})"

Enjoy

  • Related