用java写一个比对字符串差异,并返回差异内容的方法
时间: 2024-03-03 10:49:51 浏览: 180
可以使用Java的DiffUtils库来比对两个字符串之间的差异,并返回差异内容。具体实现如下:
1. 导入DiffUtils库的依赖:
```xml
<dependency>
<groupId>com.googlecode.java-diff-utils</groupId>
<artifactId>diffutils</artifactId>
<version>1.3.0</version>
</dependency>
```
2. 编写比对方法:
```java
import difflib.*;
public static String diffString(String oldStr, String newStr) {
StringBuilder diff = new StringBuilder();
List<String> original = Arrays.asList(oldStr.split("\\n"));
List<String> revised = Arrays.asList(newStr.split("\\n"));
Patch<String> patch = DiffUtils.diff(original, revised);
for (Delta<String> delta : patch.getDeltas()) {
for (Object line : delta.getOriginal().getLines()) {
diff.append("-").append(line).append("\n");
}
for (Object line : delta.getRevised().getLines()) {
diff.append("+").append(line).append("\n");
}
}
return diff.toString();
}
```
3. 调用比对方法:
```java
String oldStr = "This is the old string.";
String newStr = "This is the new string.";
String diffStr = diffString(oldStr, newStr);
System.out.println(diffStr);
```
输出结果为:
```
-This is the old string.
+This is the new string.
```
这里的比对是基于每行文本的,如果需要基于字符的比对,可以将原始字符串按字符分割成列表,然后将列表传递给DiffUtils库。
阅读全文