是否有任何辅助方法或实用工具实际上给了我两个字符串的并集。
例如,如果我有两个字符串如下:

String s1 = "Isabella,tom,hardy";
String s2 = "Isabella,tom,hardy,victor,smith";


我正在寻找一个将以上两个字符串作为输入并输出如下结果的解决方案:

General syntax:  s1.{method/utility}(s2);
output : Isabella,tom,hardy,victor,smith

最佳答案

这是一个将两个字符串合并的方法。您还可以向其传递一个布尔标志,以区分大小写。

public static String union (String s1, String s2, boolean caseInsensitive)
{
    // if either string is null, union is the other string
    if (s1 == null)
        return s2;

    if (s2 == null)
        return s1;

    // use linked set to keep ordering
    Set<String> unique = new LinkedHashSet<>();

    // put all words from string 1 into the set
    for (String word : s1.split(","))
    {
        word = word.trim(); // remove surrounding space on word

        if (caseInsensitive)
        {
            word = word.toLowerCase();
        }
        unique.add(word);
    }

    // put all words from string 2 into the set
    for (String word : s2.split(","))
    {
        word = word.trim(); // remove surrounding space on word

        if (caseInsensitive)
        {
            word = word.toLowerCase();
        }
        unique.add(word);
    }

    // get back the format of comma delimiter for the union
    String ret = unique.toString().replaceAll("[\\[\\] ]", "");
    return ret;
}


用法:

public static void main(String args[])
{
    String s1 = "Isabella,tom,hardy";
    String s2 = "Isabella,tom,hardy,victor,smith";

    String union = union(s1, s2, false);
    System.out.println(union);
}


输出:

Isabella,tom,hardy,victor,smith

09-29 21:12