简体   繁体   English

如何比较java中的2个语句

[英]How to compare 2 statements in java

Is it possible to compare 2 String like this. 是否可以像这样比较2个字符串。

String test1 = "foo bar abc";
String test2 = "bar abc foo";

Typically is not a String equals in java. 通常在java中不是String equals

I'm thinking to use ArrayList or array by splitting string by space and compare. 我想通过按空格分割字符串并比较来使用ArrayListarray

Is there any other methods available? 还有其他方法吗? which one is better? 哪一个更好?

I want answer foo bar abc and bar abc foo are the same. 我想回答foo bar abcbar abc foo是一样的。 I want to know if the same words appear in both or not. 我想知道两个是否出现相同的单词。

If your strings represent sets of words (ie collections with no duplicates), the natural solution would be to use Sets : 如果你的字符串代表单词集(即没有重复的集合),那么自然的解决方案就是使用集合

    String test1 = "foo bar abc";
    String test2 = "bar abc foo";

    HashSet<String> set1 = new HashSet<>(Arrays.asList(test1.split(" ")));
    HashSet<String> set2 = new HashSet<>(Arrays.asList(test2.split(" ")));

    System.out.println(set1.equals(set2));

You can split two strings, sort result arrays and compare them. 您可以拆分两个字符串,对结果数组进行排序并进行比较。

public static void main(String[] args) {

    String test1 = "foo bar abc";
    String test2 = "bar abc foo";

    System.out.println(method(test1, test2));
}


private static boolean method(String test1, String test2){
    String[] tokens1 = test1.split(" ");
    String[] tokens2 = test2.split(" ");

    Arrays.sort(tokens1);
    Arrays.sort(tokens2);

    return Arrays.equals(tokens1, tokens2);
}

You can make a list out of each string, by splitting both strings into separate words (using regex). 您可以通过将两个字符串拆分为单独的单词(使用正则表达式)来为每个字符串创建一个列表。
Then you can check if the second list contains all the values that are in the first list: 然后,您可以检查第二个列表是否包含第一个列表中的所有值:

String test1 = "foo bar abc";
String test2 = "bar abc foo";
List<String> list1 =Arrays.asList(test1.split("\\s+"));
List<String> list2 =Arrays.asList(test2.split("\\s+"));
if(!list2.containsAll(list1))
    return false;//or print out "false", whichever suits you

That's is one of many possibilities: 这是许多可能性之一:

import java.util.Arrays;

(...)

String test1 = "foo bar abc";
String test2 = "bar abc foo";

if (Arrays.asList(test1.split("\\s+")).containsAll(Arrays.asList(test2.split("\\s+")))) {
    return true;
} else {
    return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM