简体   繁体   English

比较两个字符串中的值

[英]Comparing values in two strings

I'm trying to compare two strings with one another. 我正在尝试比较两个字符串。 One contains for example : 其中包含例如:

String x =" aa bb cc dd ee " 

and the other one : 另一个:

String y =" aa bb "

Now I want to do this 现在我要这样做

if (any values from String x EXISTS IN String y) 

if (y.matches(???)){System.out.println("true");}
else{System.out.println("false");}

I know that I can to do the opposite by using regex, like this : 我知道我可以使用正则表达式来做相反的事情,像这样:

if (x.matches(".*"+y+".*")){do something}

But I'd like to know if there is any way to check if any value in String x matches String y. 但是我想知道是否有任何方法可以检查String x中的任何值是否与String y相匹配。

假设您所谓的“字符串中的值”是空格之间的一对字符,请拆分两个字符串以将它们转换为值集( Set<String> ),然后使用Set方法计算所需的内容( containsAll()removeAll()retainAll()等)。

If you are trying to see if String x is in String y somewhere then use the .contains(String str) method. 如果您尝试查看String x是否在某个位置的String y中,请使用.contains(String str)方法。

If you are trying to determine if the white space delimited parts of the strings are contained within y then you will need to split and then do contains on each part of the split operation. 如果要确定字符串的空格分隔部分是否包含在y内,则需要拆分,然后在拆分操作的每个部分上都包含。

String x_trimmed = x.trim();
String y_trimmed = y.trim();

String[] x_elements = x_trimmed.split("\\s+");
String[] y_elements = y_trimmed.split("\\s+");

Set<String> x_elementsSet = new HashSet<String>(Arrays.asList(x_elements));
Set<String> y_elementsSet = new HashSet<String>(Arrays.asList(y_elements));

for (String x : x_elementsSet) {
    if (y_elementsSet.contains(x)) {
       System.out.println("true");
    } else {
       System.out.println("false");
    }
}

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

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