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

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

不使用循环?


当前回答

package com;
public class _index {

    public static void main(String[] args) {
        String s1="be proud to be an indian";
        char ch=s1.charAt(s1.indexOf('e'));
        int count = 0; 
        for(int i=0;i<s1.length();i++) {
            if(s1.charAt(i)=='e'){
                System.out.println("number of E:=="+ch);
                count++;
            }
        }
        System.out.println("Total count of E:=="+count);
    }
}

其他回答

如果有人用这个;

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

结果将是true或false

这对我来说总是有效的

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

如果你在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,并尝试在一个循环中覆盖所有情况。

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

package com;
public class _index {

    public static void main(String[] args) {
        String s1="be proud to be an indian";
        char ch=s1.charAt(s1.indexOf('e'));
        int count = 0; 
        for(int i=0;i<s1.length();i++) {
            if(s1.charAt(i)=='e'){
                System.out.println("number of E:=="+ch);
                count++;
            }
        }
        System.out.println("Total count of E:=="+count);
    }
}
String temp = "abcdefghi";
if(temp.indexOf("b")!=-1)
{
   System.out.println("there is 'b' in temp string");
}
else
{
   System.out.println("there is no 'b' in temp string");
}