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.
3 Answers 3
Assuming that what you call "a value in a String" is a pair of characters between spaces, split both Strings to transform them in sets of values (Set<String>), and use the Set methods to compute what you want (containsAll(), removeAll(), retainAll(), etc.).
3 Comments
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.
2 Comments
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");
}
}
x = "aa bb cc dd ee"andy = ee aa?