How can I compare a string with smaller and smaller parts of another string?
I have a multipart string like this:
String Y = "part1 part2 part3 part4"; // This is only an example value
I want to write a functio开发者_StackOverflow社区n that compares the complete string Y with another strin, X. (Normally I will compare it with a list.) If the strings are not equal, then part1 part2 part3
should be compared with X. If they are not equal, X should be compared with part1 part2
, and then finally with just part1
.
I can use split(" ")
to break the string up. I don't know the number of chunks in the string. How can I write this comparison method?
You can use an algorithm like this:
boolean foundMatch = false;
while(!foundMatch) {
foundMatch = Y.equals(X);
if(foundMatch) {
break;
}
else {
Y = Y.useSplitToRemoveLastPart();
if(Y.equals("")) {
break;
}
}
}
That's only pseudocode, of course. It seemed like you had a general idea how to do each of these individual parts. If you need more guidance, just let me know.
EDIT:
Assuming your strings will always be space-delimited like they are in your example, you could do something like this:
String userSplitToRemoveLastPart(String Y) {
// Find the last space
int lastSpace = Y.lastIndexOf(" ");
// Return only the part of the string that comes before the last space
return Y.substring(0, lastSpace);
}
I haven't tested this, and it may not be the most efficient way to perform the split, but I think the algorithm is clear.
Something like this should get you started:
class SpecialComparator implements Comparator<String> {
public int compare(String o1, String o2) {
// Get parts to compare
String[] words1 = o1.split(" ");
String[] words2 = o2.split(" ");
// Reverse arrays to start with the last word first.
Collections.reverse(Arrays.asList(words1));
Collections.reverse(Arrays.asList(words2));
int n = Math.min(words1.length, words2.length);
for (int i = 0; i < n; i++) {
int result = words1[n].compareTo(words2[i]);
if (result != 0) // not equal, differing words found.
return result;
}
// Deal with the situation in which the strings are of different length.
// ...
// They're equal.
return 0;
}
}
I'm a little confused by your expected outcome. The goal seems to be to simply count partial matches, which this accomplishes:
public boolean foo(final String str1, final String str2) {
return Pattern.matches(" " + str1 + " (.*)", " " + str2 + " ");
}
Some tests:
String target = "part1 part2 part3 part4";
foo("part1 part2 part3 part4", target); // true
foo("part1 part2 part3", target); // true
foo("part1 part2", target); // true
foo("part1", target); // true
foo("part1 part3", target)); // false
精彩评论