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

标签 java string

我是 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/

相关文章:

ruby - 我如何检查字符串中是否存在某个单词,如果不存在,则在 ruby​​ 中返回 false?

javascript - 使用 JavaScript 删除字符串中注释标记后面的文本和空格 - 在字符串中创建新行

java - 如何更改过滤器中 http 响应的正文

java - 如何在 Hibernate 中使用单独的队列填充实体的字段?

java - 与 JOOQ 结合使用声明式事务和 TransactionAwareDataSourceProxy 的问题

python - 将一系列整数转换为字符串 - 为什么应用比 astype 快得​​多?

string - 如何将UTF-8二进制字符串转换为字符串?

java - matlab 和 java 中的 fft

java - 额外的按钮不断出现

arrays - 如何在golang中对数组中的字符串进行打乱?