How to check that the characters in two strings are the same?
How to understand this question? For example, the strings "Silent Wang Er" and "Shen Wang Ermo" The same characters are used, right? For example, the strings "Silent Wang II" and "Silent Wang III" use different characters. Do you understand?
public class CheckSameCharsInString { public static void main(String[] args) { sameCharsStrings("沉默王二", "沉王二默"); sameCharsStrings("沉默王二", "沉默王三"); } private static void sameCharsStrings(String s1, String s2) { Set<Character> set1 = s1.chars().mapToObj(c -> (char) c).collect(Collectors.toSet()); System.out.println(set1); Set<Character> set2 = s2.chars().mapToObj(c -> (char) c).collect(Collectors.toSet()); System.out.println(set2); System.out.println(set1.equals(set2)); } }
The output results are as follows:
[默, 沉, 王, 二] [默, 沉, 王, 二] true [默, 沉, 王, 二] [默, 沉, 三, 王] false
The above code uses the Stream stream. It looks strange, but it is easy to understand. It splits the string into characters and then collects them into Set. Set is a set that does not allow duplicate elements, so Just collect different characters in the string.
The above is the detailed content of How to check if characters in two strings are the same in java. For more information, please follow other related articles on the PHP Chinese website!