我有一个多部分的字符串,如下所示:
String Y = "part1 part2 part3 part4"; // This is only an example value我想编写一个函数,将完整的字符串Y与另一个字符串X进行比较(通常我会将其与列表进行比较)。如果字符串不相等,则应将part1 part2 part3与X进行比较。如果它们不相等,则应将X与part1 part2进行比较,最后仅与part1进行比较。
我可以使用split(" ")来拆分字符串。我不知道字符串中有多少块。如何编写此比较方法?
发布于 2011-03-22 04:21:58
您可以使用如下算法:
boolean foundMatch = false;
while(!foundMatch) {
foundMatch = Y.equals(X);
if(foundMatch) {
break;
}
else {
Y = Y.useSplitToRemoveLastPart();
if(Y.equals("")) {
break;
}
}
}当然,这只是伪代码。看起来你大概知道如何做每一个单独的部分。如果你需要更多的指导,请告诉我。
编辑:
假设字符串总是以空格分隔,就像在示例中一样,您可以这样做:
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);
}我还没有测试过这一点,它可能不是执行拆分的最有效的方法,但我认为算法是明确的。
发布于 2011-03-22 04:27:15
像这样的东西应该会让你开始:
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;
}
}发布于 2011-03-22 04:44:51
我对你的预期结果有点迷惑。目标似乎是简单地计算部分匹配,这就实现了:
public boolean foo(final String str1, final String str2) {
return Pattern.matches(" " + str1 + " (.*)", " " + str2 + " ");
}一些测试:
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)); // falsehttps://stackoverflow.com/questions/5383138
复制相似问题