Java String without certain characters

Introduction

Checks that the String does not contain certain characters.

containsNone(null, *)       = true
containsNone(*, null)       = true
containsNone("", *)         = true
containsNone("ab", '')      = true
containsNone("abab", 'xyz') = true
containsNone("ab1", 'xyz')  = true
containsNone("abz", 'xyz')  = false
public class Main {
  public static void main(String[] argv) throws Exception {
    String str = "demo2s.com";
    char[] invalidChars = new char[] { 'd', 'e' };
    System.out.println(containsNone(str, invalidChars));
  }//w  ww .  j av a  2s.  co  m
  public static boolean containsNone(String str, char[] invalidChars) {
    if (str == null || invalidChars == null) {
      return true;
    }
    int strSize = str.length();
    int validSize = invalidChars.length;
    for (int i = 0; i < strSize; i++) {
      char ch = str.charAt(i);
      for (int j = 0; j < validSize; j++) {
        if (invalidChars[j] == ch) {
          return false;
        }
      }
    }
    return true;
  }

  /**
   * <p>
   * Checks that the String does not contain certain characters.
   * </p>
   *
   * <p>
   * A <code>null</code> String will return <code>true</code>. A <code>null</code>
   * invalid character array will return <code>true</code>. An empty String ("")
   * always returns true.
   * </p>
   *
   * <pre>
   * containsNone(null, *)       = true
   * containsNone(*, null)       = true
   * containsNone("", *)         = true
   * containsNone("ab", "")      = true
   * containsNone("abab", "xyz") = true
   * containsNone("ab1", "xyz")  = true
   * containsNone("abz", "xyz")  = false
   * </pre>
   *
   * @param str
   *          the String to check, may be null
   * @param invalidChars
   *          a String of invalid chars, may be null
   * @return true if it contains none of the invalid chars, or is null
   * @since 2.0
   */
  public static boolean containsNone(String str, String invalidChars) {
    if (str == null || invalidChars == null) {
      return true;
    }
    return containsNone(str, invalidChars.toCharArray());
  }

}

/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */



PreviousNext

Related