Check if a string contains another string and handle nulls - Android java.lang

Android examples for java.lang:String Contains

Description

Check if a string contains another string and handle nulls

Demo Code

import java.util.List;

public class Main{
  public static final String EMPTY = ""; //$NON-NLS-1$
  public static final int INDEX_NOT_FOUND = -1;
  /**/*w ww  .  ja  v  a2s.c  o  m*/
   * <pre>
   * StringUtil.contains(null, *)    = false
   * StringUtil.contains(*, null)    = false
   * StringUtil.contains("han", "")  = true
   * StringUtil.contains("han", "h") = true
   * StringUtil.contains("han", "H") = false
   * </pre>
   * 
   */
  public static boolean contains(String str, String searchStr) {
      if (str == null || searchStr == null) {
          return false;
      }
      return str.indexOf(searchStr) > INDEX_NOT_FOUND;
  }
  public static boolean contains(String[] str, String searchStr) {
      boolean val = false;
      if (str == null || searchStr == null) {
          return val;
      }
      for (String s : str) {
          if (equals(s, searchStr)) {
              val = true;
              break;
          }
      }
      return val;
  }
  public static boolean equals(String str1, String str2) {
    return str1 == null ? str2 == null : str1.equals(str2);
}
  /**
   * <pre>
   * StringUtil.contains("han", {"a", "b"}) = true
   * StringUtil.contains("han", {"aa", "bb"}) = false
   * </pre>
   * 
   * @return
   */
  public static boolean contains(String str, List<String> keywords) {
      if (str == null || keywords == null) {
          return false;
      }

      for (String key : keywords) {
          if (contains(str, key)) {
              return true;
          }
      }

      return false;
  }
}

Related Tutorials