how to check if a string contains a character in java?

To check if a string contains a specific character in Java, the following ways can be used-

The java String's contains() method checks for a particular sequence of characters present within a string. It returns true if the specified character sequence is present within the string, otherwise, it returns false.

The contains() method is case-sensitive.

public static void main(String[] args) {
        String str = "Example";
        System.out.println(str.contains("x"));
        System.out.println(str.contains("X"));
       
    }

Output-

true
false

By using indexOf() method -

While the contains() method returns a boolean value, the indexOf() method returns an int type value which is actually the index of the substring or character within the string.

The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it returns -1.

For example "Hello World".indexOf("World") will return 6 but "Hello World".indexOf("world") will return -1.

public static void main(String[] args) {
        String str = "Chercher Tech";
       //remember that indexOf() method is case sensitive
        System.out.println("The position of Tech is "+str.indexOf("Tech" )); 
}

Output-

The position of Tech is 9

Using charAt() method and a loop -

We will execute a loop throughout the string length to find the match for the particular character-

public static void main(String[] args) {
  String str = "example";
  char[] findChar = {'x','a'};
  for (int i = 0; i < str.length(); i++) {
    char ch = str.charAt(i);
    for (int j = 0; j < findChar.length; j++) {
      if (findChar[j] == ch) {
        System.out.println("The character " +findChar[j] + " is present in " + str);
      }
    }
  }
}

Output-

The character x is present in example
The character a is present in example
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions