在 java 中的字符串中交换两个子字符串
Swap two substring in a string in java
我正在尝试分析一些文本,我需要交换字符串中的两个子字符串,例如在下面的文本中我想交换 "nice to see you" 和 "how are you"
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),但它不会说话。
还有其他方法吗?
试试这个:
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());
我正在尝试分析一些文本,我需要交换字符串中的两个子字符串,例如在下面的文本中我想交换 "nice to see you" 和 "how are you"
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),但它不会说话。
还有其他方法吗?
试试这个:
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());