Bastiano Coimbra
Bastiano Coimbra

Reputation: 11

Delete a specific char in a String

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;
}  

Upvotes: 1

Views: 100

Answers (1)

Maurice Perry
Maurice Perry

Reputation: 9651

Try this:

public String zipZap(String str) {
    return str.replaceAll("z[a-z]p", "zp");
}

Upvotes: 3

Related Questions