【问题标题】:Find relevant parts in a collection of strings在字符串集合中查找相关部分
【发布时间】:2016-02-24 06:50:44
【问题描述】:

我有一组路径字符串:

/content/example-site/global/library/about/contact/thank-you.html
/content/example-site/global/corporate/about/contact/thank-you.html
/content/example-site/countries/uk/about/contact/thank-you.html
/content/example-site/countries/de/about/contact/thank-you.html
/content/example-site/others/about/contact/thank-you.html
...

(通常路径比这长得多)

如您所见,很难立即注意到差异。这就是为什么我想突出显示字符串中的相关部分。

为了找出差异,我目前计算了所有字符串的公共前缀和后缀:

String prefix = getCommonPrefix(paths);
String suffix = getCommonSuffix(paths);
for (String path : paths) {
    String relevantPath = path.substring(prefix.length(), path.length() - suffix.length());
    // OUTPUT: prefix + "<b>" + relevantPath + "</b>" + suffix
}

对于我使用 Commons Lang 中的 StringUtils.getCommonPrefix 的前缀。

对于后缀,我找不到实用程序(在 Commons 和 Guava 中都没有,后者只有一个用于正好两个字符串)。所以我必须自己写 - 类似于 Commons Lang 的。

我现在想知道,如果我错过了其中一个库中的某些功能 - 或者 是否有使用 Java 8 流式处理函数的简单方法?

【问题讨论】:

    标签: java java-8 apache-commons-lang3


    【解决方案1】:

    这里有一个小技巧,我并不是说它是最佳的,也不是什么都不是,但如果没有其他选项可用,沿着这条路走可能会很有趣:

    String[] reversedPaths = new String[paths.length];
    for (int i = 0; i < paths.length; i++) {
        reversedPaths[i] = StringUtils.reverse(paths[i]);
    }
    String suffix = StringUtils.reverse(StringUtils.getCommonPrefix(reversedPaths));
    

    【讨论】:

    • 我用StringUtils.reverse 替换了StringBuilder.reverse,因为它的作用相同,而且阅读起来更好一些。我删除了 Solution 标题,以减轻我立即接受它的压力;-)
    • @TobiasLiefke 没问题。我不知道 StringUtils 有这样的方法。每天学习:)
    【解决方案2】:

    你可以反转每条路径,找到这些反转后的字符串的前缀,并将所述前缀反转得到一个共同的后缀。
    像这样:

    String commonSuffix = new StringBuffer(getCommonPrefix(paths.stream().map(path -> new StringBuffer(path).reverse().toString()).collect(Collectors.toList()))).reverse().toString();
    

    我个人不太喜欢这个解决方案,因为您为列表中的每个路径创建了一个新的 StringBuffer。这就是java有时的工作方式,但如果对性能没有危险的话,它至少是丑陋的。你可以编写你自己的函数

    public static String invert(String s) { // invert s using char[] }
    

    如果你愿意。

    【讨论】:

    • 您应该使用StringBuilder 而不是StringBuffer(请参阅stackoverflow.com/questions/355089/…)。编写我自己的反转函数不会让它更快(我只会为new StringBuilder 保留最初的char[] 副本)。但是,如果您改用StringUtils.inverse 并考虑到getCommonPrefix 期待String[],我会说这是Java 8 的有效解决方案。我不会为此责怪Java,因为我不知道一种语言,它为你能想到的每一个字符串操作提供一个助手......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    • 2021-01-26
    相关资源
    最近更新 更多