在java中交换字符串中的两个子字符串

问题描述 投票:3回答:1

我正在尝试分析一些文本,我需要在一个字符串中交换两个子字符串,例如在下面的文本中我想交换“很高兴见到你”和“你好吗”

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

所以结果应该是:

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

首先,我编写了这个方法,并且可以正常运行这个简单的例

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

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

    return source;
}

我需要将此方法用于更复杂的文本,如下所示,但由于replaceFirst使用正则表达式,因此无法使用我的方法进行交换。

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

我想交换f(x)和g(x),但它不会说话。

还有其他办法吗?

java string swap
1个回答
3
投票

试试这个:

source=source.replace(str1, str2);

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

请参阅Pattern.quote here的文档。

请参阅Matcher.quoteReplacement here的文档。

警告:您选择的这种方法有两个很大的假设!

  • 假设#1:str2必须出现在str1之前的源头,并且
  • 假设#2:str2只能在源字符串中出现一次
  • 此外:如果其中一个字符串是另一个字符串的子字符串,您将得到意外的结果

需要更多的general solution来消除这些问题。

例如:

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());
© www.soinside.com 2019 - 2024. All rights reserved.