itaik
itaik

Reputation: 315

Find a pattern at certain location in a String and replace it with something else in Java

I’m facing a weird problem that I cant resolve for some reason. If I have this String: “aaaa aa” And the pattern is: “aa” So there is 3 places that match that pattern: (aa)(aa)( aa) I want to change the pattern at specific location (let’s say at the second position) with something else, let’s say this String: “bbb”.

So the final result will be: “aabbb aa”.

What is the simplest way to solve this? Without any special collection or special classes.

Upvotes: 3

Views: 236

Answers (2)

rzwitserloot
rzwitserloot

Reputation: 103473

The String class has an indexOf method. This method comes in two variants: One where you just specify the needle (the string you want to search), and the method returns the position of the first character in the haystack (the string you are searching) which matches your pattern.

The second variant takes two parameters: The pattern, and the position at which to start.

So, you can do something like this:

void replaceSecondOccurrence(String haystack, String needle, String replacement) {
    int occurenceToReplace = 2;
    int pos = -1;
    while (true) {
        pos = haystack.indexOf(needle, pos + 1);
        if (pos == -1) {
            // There is no second occurence. Just return the haystack.
            return haystack;
        }
        if (--occurenceToReplace == 0) return
            haystack.substring(0, pos) +
            replacement +
            haystack.substring(pos + needle.length());
    }
}

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522346

One option would be to use a formal regex pattern matcher, and then iterate the input string, looking for aa matches. When we hit the second match, then do a substitution of aa for bb, otherwise just substitute with aa, the original value.

String input = "aaaa aa";
Pattern pattern = Pattern.compile("aa");
Matcher matcher = pattern.matcher(input);
StringBuffer buffer = new StringBuffer();

int num = 0;
while(matcher.find()) {
    String replace = num == 1 ? "bbb" : "aa";
    matcher.appendReplacement(buffer, replace);
    ++num;
}

matcher.appendTail(buffer);
System.out.println(buffer.toString());

aabbb aa

Upvotes: 2

Related Questions