gpt4 book ai didi

java - 与具有相同字符或字母的字符串进行比较

转载 作者:行者123 更新时间:2023-11-29 03:23:41 24 4
gpt4 key购买 nike

我是 Java 编程的新手,最近开始研究字符串操作。
谁能建议我一个可行的想法来检查字符串是否由相同的字符集组成?

例子:

string1="add" so string1 has characters "a,d"
string2="dad" so string2 has characters "a,d"
--> they match

String1="abc"
string2="abcd"
--> they don't match

我不想逐字比较

最佳答案

听起来您正在尝试检查一个字符串中包含的字符集是否与另一个字符串中包含的字符集相同。使用 Set<Character> 很容易实现这一点:

static boolean characterSetsEqual(String text1, String text2) {
Set<Character> set1 = toCharacterSet(text1);
Set<Character> set2 = toCharacterSet(text2);
return set1.equals(set2);
}

static Set<Character> toCharacterSet(String input) {
Set<Character> set = new HashSet<>();
for (int i = 0; i < input.length(); i++) {
set.add(input.charAt(i));
}
return set;
}

Set<>.equals 完全按照您希望的方式定义:

Compares the specified object with this set for equality. Returns true if the specified object is also a set, the two sets have the same size, and every member of the specified set is contained in this set (or equivalently, every member of this set is contained in the specified set). This definition ensures that the equals method works properly across different implementations of the set interface.

重要的是要看到你真的对这里的集合感兴趣——从 String 的转换(这是一个字符序列)转换成 Set<Character> (没有固有顺序,也没有计算每个字符出现的次数)是关键部分。

关于java - 与具有相同字符或字母的字符串进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22192592/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com