1

I try to solve some String tasks but I have some problems. I don´t understand how i search for 2 different chars and delete if 1 char is between of this 2 chars.

My task is:

Look for patterns like "zip" and "zap" in the string -- length-3, starting with 'z' and ending with 'p'. Return a string where for all such words, the middle letter is gone, so "zipXzap" yields "zpXzp". My code is:

public String zipZap(String str) {
    char z = 'z';
    char p = 'p';

    for (int i = str.indexOf('z', 0); i != -1; i = str.indexOf('z', 1)) {
        for (int j = str.indexOf('p', 0); i != -1; i = str.indexOf('p', 1)) {
           if (p = i + 2) {
               str = str.replace(i + 1, " ");
           }
        }
    }

    return str;
}  
2
  • 2
    Search what are regex for. Commented Dec 10, 2018 at 14:33
  • Please learn and practice correct indentation because that is very difficult to read. Commented Dec 10, 2018 at 14:36

1 Answer 1

3

Try this:

public String zipZap(String str) {
    return str.replaceAll("z[a-z]p", "zp");
}
Sign up to request clarification or add additional context in comments.

1 Comment

Worth mentioning that this one replaces only small letters. @Bastiano Coimbra might want to replace any character

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.