Search code examples
javastringswap

Swap two substring in a string in java


I'm trying to analyze some text and I need to swap two substring in a string, for example in the following text I wanna swap "nice to see you" and "how are you"

Hi nice to see you? I'm fine Nice! how are you some other text

so the result should be :

Hi how are you? I'm fine Nice! nice to see you some other text

First I wrote this method and works fine for this simple example:

    public static String Swap(String source, String str1, String str2) {

    source=source.replace(str1, str2);
    source=source.replaceFirst(str2, str1);

    return source;
}

I need to use this method for more complex texts like the following one but as replaceFirst uses regex it cannot swap using my method.

        f(f(x))*g(g(x))

I wanna swap f(x) and g(x), but it won't word.

is there any other way to do this?


Solution

  • Try this:

    source=source.replace(str1, str2);
    
    // handle things like "f(f(x))*g(g(x))"
    source=source.replaceFirst(Pattern.quote​(str2), Matcher.quoteReplacement(str1));
    

    See the documentation for Pattern.quote here.

    See the documentation for Matcher.quoteReplacement here.

    Warning: This approach you have chosen has two big assumptions!

    • Assumption #1: str2 must appear in the source before str1, and
    • Assumption #2: str2 must only appear one time in the source string
    • Furthermore: if one of the strings is a substring of the other, you will get unexpected results

    A more general solution would be needed to eliminate those problems.

    For example:

    String longer = str1;
    String shorter = str2;
    if(str2.length() > str1.length()) {
        longer = str2;
        shorter = str1;
    }
    Pattern p = Pattern.compile(Pattern.quote(longer) + "|" + Pattern.quote(shorter));
    Matcher m = p.matcher(source);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        String replacement = str1;
        if(m.group(0).equals(str1)) {
            replacement = str2;
        }
        m.appendReplacement(sb, Matcher.quoteReplacement(replacement));
    }
    m.appendTail(sb);
    System.out.println(sb.toString());