如何将字符串与另一个字符串的较小和较小部分进行比较?

时间:2011-03-21 20:19:01

标签: java compare

我有一个像这样的多部分字符串:

String Y = "part1 part2 part3 part4"; // This is only an example value

我想编写一个函数,将完整的字符串Y与另一个strin X进行比较。(通常我会将它与列表进行比较。)如果字符串不相等,则应将part1 part2 part3与X进行比较如果它们不相等,则应将X与part1 part2进行比较,最后再与part1进行比较。

我可以使用split(" ")打破字符串。我不知道字符串中的块数。我该如何编写这种比较方法?

3 个答案:

答案 0 :(得分:3)

你可以使用这样的算法:

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);
}

我没有对此进行测试,并且可能是执行拆分的最有效方式,但我认为算法很明确。

答案 1 :(得分:1)

这样的事情应该让你开始:

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;
    }
}

答案 2 :(得分:1)

我对你的预期结果感到有些困惑。目标似乎是简单地计算部分匹配,这实现了:

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)); // false