Home > Java > javaTutorial > How to check if characters in two strings are the same in java

How to check if characters in two strings are the same in java

WBOY
Release: 2023-04-19 17:04:07
forward
1979 people have browsed it

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));     } }
Copy after login

The output results are as follows:

[默, 沉, 王, 二]  [默, 沉, 王, 二]  true  [默, 沉, 王, 二]  [默, 沉, 三, 王]  false
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template