gpt4 book ai didi

java - 在存储在哈希集中的生成代码中查找单词

转载 作者:行者123 更新时间:2023-12-01 19:48:16 24 4
gpt4 key购买 nike

生成代码示例:910love009tre

我想检查生成的代码中是否包含特定单词。我正在尝试使用 contains 方法,但看起来它没有给我所需的输出。

import java.security.SecureRandom;
import java.util.HashSet;
import java.util.Set;

public class AlphaNumericExample {
public static void main(String[] args) {

enter code here
AlphaNumericExample example = new AlphaNumericExample();
Set<String> codes = new HashSet<>();
for (int x = 0;x< 100 ;x++ ) {

codes.add(example.getAlphaNumeric(16));
System.out.println(codes.contains("love"));//Im trying to check if the generated codes that have been stored in hashset have form a word
}

System.out.println("Size of the set: "+codes.size());


}

public String getAlphaNumeric(int len) {

char[] ch = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();

char[] c = new char[len];
SecureRandom random = new SecureRandom();//
for (int i = 0; i < len; i++) {
c[i] = ch[random.nextInt(ch.length)];
}

return new String(c);
}
}

最佳答案

在这种情况下,contains 方法检查整个对象是否匹配。如果它包含特定的字符序列则不会,因此 13 个字符的对象永远不会匹配 4 个字母的序列

而不是

System.out.println(codes.contains("love"));//Im trying to check if the generated codes that have been stored in hashset have form a word 

尝试对每个单独的字符串使用 contains 方法,而不是 HashSet 的 contains 方法

for (String code: codes) { 
if (code.contains("love") {
System.out.println("found!")
}
}

关于java - 在存储在哈希集中的生成代码中查找单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52405104/

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