简体   繁体   中英

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.

假设您所谓的“字符串中的值”是空格之间的一对字符,请拆分两个字符串以将它们转换为值集( 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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