在Java中有一种方法来检查条件:

"这个字符是否出现在字符串x中"

不使用循环?


当前回答

要检查字符串中是否存在某些东西,您至少需要查看字符串中的每个字符。所以即使你没有显式地使用循环,它也会有同样的效率。也就是说,您可以尝试使用str.contains(""+char)。

其他回答

string .contains()检查字符串是否包含指定的char值序列 string . indexof()返回字符串中第一次出现指定字符或子字符串的索引(此方法有4种变体)

如果有人用这个;

let text = "Hello world, welcome to the universe.";
let result = text.includes("world");
console.log(result) ....// true

结果将是true或false

这对我来说总是有效的

是的,在字符串类上使用indexOf()方法。请参阅此方法的API文档

如果您需要经常检查相同的字符串,您可以预先计算字符出现的次数。这是一个使用位数组包含在长数组中的实现:

public class FastCharacterInStringChecker implements Serializable {
private static final long serialVersionUID = 1L;

private final long[] l = new long[1024]; // 65536 / 64 = 1024

public FastCharacterInStringChecker(final String string) {
    for (final char c: string.toCharArray()) {
        final int index = c >> 6;
        final int value = c - (index << 6);
        l[index] |= 1L << value;
    }
}

public boolean contains(final char c) {
    final int index = c >> 6; // c / 64
    final int value = c - (index << 6); // c - (index * 64)
    return (l[index] & (1L << value)) != 0;
}}
you can use this code. It will check the char is present or not. If it is present then the return value is >= 0 otherwise it's -1. Here I am printing alphabets that is not present in the input.

import java.util.Scanner;

public class Test {

public static void letters()
{
    System.out.println("Enter input char");
    Scanner sc = new Scanner(System.in);
    String input = sc.next();
    System.out.println("Output : ");
    for (char alphabet = 'A'; alphabet <= 'Z'; alphabet++) {
            if(input.toUpperCase().indexOf(alphabet) < 0) 
                System.out.print(alphabet + " ");
    }
}
public static void main(String[] args) {
    letters();
}

}

//Ouput Example
Enter input char
nandu
Output : 
B C E F G H I J K L M O P Q R S T V W X Y Z