Java String contain a character

Introduction

Checks if String contains a search character, handling null.

This method uses String#indexOf(int).

contains(null, *)    = false
contains("", *)      = false
contains("abc", 'a') = true
contains("abc", 'z') = false
public class Main {
  public static void main(String[] argv) throws Exception {
    String str = "demo2s.com";
    char searchChar = 'a';
    System.out.println(contains(str, searchChar));
  }//w w  w  .  j av a 2s .c  o m
  public static boolean contains(String str, char searchChar) {
    if (isEmpty(str)) {
      return false;
    }
    return str.indexOf(searchChar) >= 0;
  }

  public static boolean isEmpty(String str) {
    return str == null || str.length() == 0;
  }
}



PreviousNext

Related