Java – What is equivalent to .replaceSecond or .replaceThird?

What is equivalent to .replaceSecond or .replaceThird?… here is a solution to the problem.

What is equivalent to .replaceSecond or .replaceThird?

In this code, we use the .replaceFirst method to remove the substring “luna” from the email string. We are removing the character between + and @. But this only happens in the first instance because we used .replaceFirst. What if we want to remove “smith” against the second instance of + and @?
Our output now is alice+@john+smith@steve+oliver@ but we want alice+luna@john+@steve+oliver@

public class Main {

public static void main(String[] args) {

String email = "alice+luna@john+smith@steve+oliver@";

String newEmail = email.replaceFirst("\\+.*?@", "");

System.out.println(newEmail);

}
}

Solution

You can find the second +:: like this

int firstPlus = email.indexOf('+');
int secondPlus = email.indexOf('+', firstPlus + 1);

(If necessary, you’ll need to handle cases where there are no two + lookups).

Then find @:

int at = email.indexOf('@', secondPlus);

Then stitch it up :

String newEmail = email.substring(0, secondPlus + 1) + email.substring(at);

or

String newEmail2 = new StringBuilder(email).delete(secondPlus + 1, at).toString();

Ideone demo

Related Problems and Solutions