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

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

不使用循环?


当前回答

我不确定最初的海报到底想要什么。由于indexOf(…)和contains(…)都可能在内部使用循环,也许他想看看如果没有循环这是否可行?我可以想到两种方法,一种当然是递归

public boolean containsChar(String s, char search) {
    if (s.length() == 0)
        return false;
    else
        return s.charAt(0) == search || containsChar(s.substring(1), search);
}

另一个远没有那么优雅,但完整…:

/**
 * Works for strings of up to 5 characters
 */
public boolean containsChar(String s, char search) {
    if (s.length() > 5) throw IllegalArgumentException();

    try {
        if (s.charAt(0) == search) return true;
        if (s.charAt(1) == search) return true;
        if (s.charAt(2) == search) return true;
        if (s.charAt(3) == search) return true;
        if (s.charAt(4) == search) return true;
    } catch (IndexOutOfBoundsException e) {
        // this should never happen...
        return false;
    }
    return false;
}

当然,行数会随着您需要支持越来越长的字符串而增长。但是根本没有循环/递归。如果您担心length()使用循环,您甚至可以删除长度检查。

其他回答

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");
}
static String removeOccurences(String a, String b)
{
    StringBuilder s2 = new StringBuilder(a);

    for(int i=0;i<b.length();i++){
        char ch = b.charAt(i);  
        System.out.println(ch+"  first index"+a.indexOf(ch));

        int lastind = a.lastIndexOf(ch);

    for(int k=new String(s2).indexOf(ch);k > 0;k=new String(s2).indexOf(ch)){
            if(s2.charAt(k) == ch){
                s2.deleteCharAt(k);
        System.out.println("val of s2 :             "+s2.toString());
            }
        }
      }

    System.out.println(s1.toString());

    return (s1.toString());
}

我不确定最初的海报到底想要什么。由于indexOf(…)和contains(…)都可能在内部使用循环,也许他想看看如果没有循环这是否可行?我可以想到两种方法,一种当然是递归

public boolean containsChar(String s, char search) {
    if (s.length() == 0)
        return false;
    else
        return s.charAt(0) == search || containsChar(s.substring(1), search);
}

另一个远没有那么优雅,但完整…:

/**
 * Works for strings of up to 5 characters
 */
public boolean containsChar(String s, char search) {
    if (s.length() > 5) throw IllegalArgumentException();

    try {
        if (s.charAt(0) == search) return true;
        if (s.charAt(1) == search) return true;
        if (s.charAt(2) == search) return true;
        if (s.charAt(3) == search) return true;
        if (s.charAt(4) == search) return true;
    } catch (IndexOutOfBoundsException e) {
        // this should never happen...
        return false;
    }
    return false;
}

当然,行数会随着您需要支持越来越长的字符串而增长。但是根本没有循环/递归。如果您担心length()使用循环,您甚至可以删除长度检查。

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

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