我正在开发一个Java应用程序,它是用来记笔记的。现在,每当用户编辑笔记中的文本时,我都想找到oldText和newText之间的区别,这样我就可以将其添加到该笔记的历史记录中。
为此,我将每个段落分割成多个字符串,在点处进行拆分。然后我使用diff-match补丁比较字符串列表中的句子。
到目前为止,它可以在文本中添加、编辑,但一旦我删除一个句子,就会出现问题。
情况是
old text : sentence1, sentence2, sentence3, sentence4
new Text : sentence1, sentence3, sentence4.
但正因为如此,比较器看到句子2被句子3取代,句子3被句子4取代,以此类推。
这不是我想要的行为,但我不知道如何补救这种情况。我会发布我的代码,请告诉我如何正确地获取它们之间的差异。
GroupNoteHistory是我保存oldText和newText更改的对象。我希望我的代码可以理解。
// Below is List of oldText and newText splitted at dot.
List<String> oldTextList = Arrays.asList(mnotes1.getMnotetext().split("(\.|\n)"));
List<String> newTextList = Arrays.asList(mnotes.getMnotetext().split("(\.|\n)"));
// Calculating the size of loop.
int counter = Math.max(oldTextList.size(), newTextList.size());
String oldString;
String newString;
for (int current = 0; current < counter; current++) {
oldString = "";
newString = "";
if (oldTextList.size() <= current) {
oldString = "";
newString = newTextList.get(current);
} else if (newTextList.size() <= current) {
oldString = oldTextList.get(current);
newString = "";
} else {
// isLineDifferent comes from diff_match_patch
if (isLineDifferent(oldTextList.get(current), newTextList.get(current))) {
noEdit = true;
groupNoteHistory.setWhatHasChanged("textchange");
oldString += oldTextList.get(current);
newString += newTextList.get(current);
}
}
if (oldString != null && newString != null) {
if (!(groupNoteHistory.getNewNoteText() == null)) {
if (!(newString.isEmpty())) {
groupNoteHistory.setNewNoteText(groupNoteHistory.getNewNoteText() + " " + newString);
}
} else {
groupNoteHistory.setNewNoteText(newString);
}
if (!(groupNoteHistory.getOldText() == null)) {
if (!(oldString.isEmpty())) {
groupNoteHistory.setOldText(groupNoteHistory.getOldText() + " " + oldString);
}
} else {
groupNoteHistory.setOldText(oldString);
}
}
请让我知道我能做什么。非常感谢。:-)
您可以使用一个库,即:https://code.google.com/p/java-diff-utils/
您可以使用它的DiffUtils.diff方法添加句子作为输入,它应该完全符合您的要求,请参阅下面的测试。
import difflib.Delta;
import difflib.DiffUtils;
import difflib.Patch;
import org.junit.Test;
import java.util.Arrays;
public class DiffUtilsTest {
public String note1 = "Sentence 1, sentence 2, sentence 3, sentence 4";
public String note2 = "Sentence 1, sentence 3, sentence 5";
@Test
public void testDiff() {
Patch<String> patch = DiffUtils.diff(Arrays.asList(note1.split("[\.,]")), Arrays.asList(note2.split("[\.,]")));
for (Delta<String> delta: patch.getDeltas()) {
System.out.println(delta);
};
//outputs
//[DeleteDelta, position: 1, lines: [ sentence 2]]
//[ChangeDelta, position: 3, lines: [ sentence 4] to [ sentence 5]]
}
}