Check if a string contains Only the char from a char array - Java java.lang

Java examples for java.lang:String Contain

Description

Check if a string contains Only the char from a char array

Demo Code

//package com.java2s;

public class Main {
  public static void main(String[] argv) {
    String str = "java2s.com";
    char[] valid = new char[] { 'b', 'o', 'o', 'k', '2', 's', '.', 'c', 'o', 'm', 'a', '1', };
    System.out.println(containsOnly(str, valid));
  }/*from  ww w.  j a  va 2s. c o  m*/

  public static boolean containsOnly(String str, char[] valid) {
    if ((valid == null) || (str == null)) {
      return false;
    }

    if (str.length() == 0) {
      return true;
    }

    if (valid.length == 0) {
      return false;
    }

    return indexOfAnyBut(str, valid) == -1;
  }

  public static boolean containsOnly(String str, String valid) {
    if ((str == null) || (valid == null)) {
      return false;
    }

    return containsOnly(str, valid.toCharArray());
  }

  public static int indexOfAnyBut(String str, char[] searchChars) {
    if ((str == null) || (str.length() == 0) || (searchChars == null) || (searchChars.length == 0)) {
      return -1;
    }

    outer: for (int i = 0; i < str.length(); i++) {
      char ch = str.charAt(i);

      for (int j = 0; j < searchChars.length; j++) {
        if (searchChars[j] == ch) {
          continue outer;
        }
      }

      return i;
    }

    return -1;
  }

}

Related Tutorials