I have read almost all similar topics but haven't found a working solution for my case. Sorry for posting similar question again.
Let's imagine I have two strings:
String string1 = "this is my string ";
String string2 = "this is not my string that I want";
In my case I want my string2 to be equal to string1
To do so I need to remove not and that I want parts from string2 while collecting these mismatchings.
As a result I would like to have something like this in my code:
List<String> mismatchings = ...; // consists of "not" and "that I want"
String string2Adjusted = "this is my string "; // string2 after adjustment
Is there any util to do so, Or I might need to do some hard stuff with strings myself?
CodePudding user response:
This compares at the word level, if it is not sufficient and you want to compare at the character level, you just need to change the split parameter to an empty string.
public static void main(String[] args) {
String string1 = "this is my string ";
String string2 = "this is not my string that I want";
String[] str1Parts = string1.split("\s ");
String[] str2Parts = string2.split("\s ");
ArrayList<String> missMatches = new ArrayList<>();
int i = 0;
for (String part: str1Parts) {
for (; i < str2Parts.length; i ) {
String toCompare = str2Parts[i];
if (!part.equals(toCompare)) {
missMatches.add(toCompare);
continue;
}
i ;
break;
}
}
StringBuilder rest = new StringBuilder();
for (int start = i; i < str2Parts.length; i ) {
if (start != i)
rest.append(" ");
rest.append(str2Parts[i]);
}
missMatches.add(rest.toString());
for (String missMatched: missMatches) {
System.out.println(missMatched);
}
}
CodePudding user response:
After researching of existing utilities I stopped at:
<dependency>
<groupId>org.bitbucket.cowwoc</groupId>
<artifactId>diff-match-patch</artifactId>
<version>1.2</version>
</dependency>
With this 3rd-party library solution the result is as expected:
List<String> diff = new DiffMatchPatch().diffMain(string1, string2, false).stream()
.filter(d -> d.operation.equals(DiffMatchPatch.Operation.INSERT))
.map(d -> d.text)
.collect(Collectors.toList());
System.out.println(diff);