Java - Write code to Checks if the String contains any character in the given set of characters.

Requirements

Write code to Checks if the String contains any character in the given set of characters.

containsAny(null, *)                = false
containsAny("", *)                  = false
containsAny(*, null)                = false
containsAny(*, [])                  = false
containsAny("zzabyycdxx",['z','a']) = true
containsAny("zzabyycdxx",['b','y']) = true
containsAny("aba", ['z'])           = false

Hint

Use nested for loop

Demo

public class Main{
    public static void main(String[] argv){
        String str = "book2s.com";
        char[] searchChars = new char[]{'b','o','o','k','2','s','.','c','o','m','a','1',};
        System.out.println(containsAny(str,searchChars));
    }/*from  w  w  w  .ja  v  a 2s. co  m*/
    /**
     * <p>
     * Checks if the String contains any character in the given set of
     * characters.
     * </p>
     * 
     * <p>
     * A <code>null</code> String will return <code>false</code>. A
     * <code>null</code> or zero length search array will return
     * <code>false</code>.
     * </p>
     * 
     * <pre>
     * containsAny(null, *)                = false
     * containsAny("", *)                  = false
     * containsAny(*, null)                = false
     * containsAny(*, [])                  = false
     * containsAny("zzabyycdxx",['z','a']) = true
     * containsAny("zzabyycdxx",['b','y']) = true
     * containsAny("aba", ['z'])           = false
     * </pre>
     * 
     * @param str
     *            the String to check, may be null
     * @param searchChars
     *            the chars to search for, may be null
     * @return the <code>true</code> if any of the chars are found,
     *         <code>false</code> if no match or null input
     * @since 2.4
     */
    public static boolean containsAny(String str, char[] searchChars) {
        int csLength = str.length();
        int searchLength = searchChars.length;
        for (int i = 0; i < csLength; i++) {
            char ch = str.charAt(i);
            for (int j = 0; j < searchLength; j++) {
                if (searchChars[j] == ch) {
                    return true;
                }
            }
        }
        return false;
    }
}

Related Example