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

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

不使用循环?


当前回答

这是你要找的吗?

int index = string.indexOf(character);
return index != -1;

其他回答

如果你在JAVA中看到indexOf的源代码:

public int indexOf(int ch, int fromIndex) {

        final int max = value.length;

        if (fromIndex < 0) {

            fromIndex = 0;

        } else if (fromIndex >= max) {

            // Note: fromIndex might be near -1>>>1.

            return -1;

        }


        if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {

            // handle most cases here (ch is a BMP code point or a

            // negative value (invalid code point))

            final char[] value = this.value;

            for (int i = fromIndex; i < max; i++) {

                if (value[i] == ch) {

                    return i;

                }

            }

            return -1;

        } else {

            return indexOfSupplementary(ch, fromIndex);

        }

    }

你可以看到它使用for循环来查找字符。注意,在代码中使用的每个indexOf都等于一个循环。

因此,对于单个字符使用循环是不可避免的。

但是,如果您想找到具有更多不同形式的特殊字符串,请使用有用的库,如util。regex,它部署了更强的算法来匹配字符或字符串模式与正则表达式。例如,在字符串中查找电子邮件:

String regex = "^(.+)@(.+)$";
 
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(email);

如果你不喜欢使用正则表达式,只需使用循环和charAt,并尝试在一个循环中覆盖所有情况。

注意递归方法比循环方法有更多的开销,所以不推荐使用。

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

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;
}}

这是你要找的吗?

int index = string.indexOf(character);
return index != -1;

如果有人用这个;

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

结果将是true或false

这对我来说总是有效的

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