How to Check if a String Contains Character in Java

Payel Ganguly Feb 02, 2024
  1. Use the contains() Method to Check if a String Contains a Character
  2. Use String indexOf() Method to Check if a String Contains Character
  3. Use the Enhanced for Loop to Check if a String Contains Character
  4. Use Java Streams anyMatch() Method to Check if a String Contains a Character
  5. Use the matches() Method With Regular Expressions to Check if a String Contains Character
  6. Conclusion
How to Check if a String Contains Character in Java

String manipulation is a fundamental aspect of programming, and in Java, determining whether a string contains a specific character is a common requirement. Fortunately, Java provides several methods to achieve this task, each catering to different needs.

In this article, we’ll explore various approaches to check if a string contains a particular character.

Use the contains() Method to Check if a String Contains a Character

The contains() method is a member of the String class in Java. It returns a boolean value, indicating whether the specified character sequence occurs within the string.

The syntax of the contains() method is as follows:

boolean contains(CharSequence sequence)

Here, sequence represents the character sequence to be checked for existence within the string. It can be a single character or a longer sequence.

Let’s walk through a simple example to illustrate how to use the contains() method to check if a string contains a specific character.

public class StringContainmentExample {
  public static void main(String[] args) {
    String str = "Hello, World!";
    char targetChar = 'o';

    if (str.contains(String.valueOf(targetChar))) {
      System.out.println("String contains the character " + targetChar);
    } else {
      System.out.println("String does not contain the character " + targetChar);
    }
  }
}

Output:

String contains the character o

In the provided Java example, we illustrate how to check if a string contains a specific character using the contains() method.

The process begins with the initialization of a string variable, str, and the specification of the target character, targetChar.

The contains() method is then invoked on the string, passing String.valueOf(targetChar) as its parameter to convert the target character into a string. This conversion is necessary as the contains() method expects a CharSequence.

Following the method call, a conditional check is performed.

  • If the result is true, indicating that the string contains the specified character, a corresponding message is printed.
  • Conversely, if the result is false, indicating the absence of the character, a different message is printed.

It’s essential to note that the contains() method in Java is case-sensitive. This means that it distinguishes between uppercase and lowercase characters.

For example, if we were to search for an uppercase O in our string, it would return false since our string contains only lowercase o.

To perform a case-insensitive check, we can convert both the string and the target character to lowercase (or uppercase) using methods like toLowerCase() or toUpperCase() before applying the contains() method.

Here’s an example code:

public class CaseSensitivityExample {
  public static void main(String[] args) {
    String str = "Hello, World!";
    char targetUpperCaseChar = 'O';

    if (str.toLowerCase().contains(String.valueOf(targetUpperCaseChar).toLowerCase())) {
      System.out.println(
          "String contains the character " + targetUpperCaseChar + " (case-insensitive)");
    } else {
      System.out.println(
          "String does not contain the character " + targetUpperCaseChar + " (case-insensitive)");
    }
  }
}

Output:

String contains the character O (case-insensitive)

In this example, we have a string str containing Hello, World! and a target character O. We perform a case-insensitive check by converting both the string and the target character to lowercase using the toLowerCase() method before applying the contains() method.

Use String indexOf() Method to Check if a String Contains Character

The indexOf() method is a versatile tool that belongs to the String class in Java. It returns the index of the first occurrence of a specified character or substring within the given string.

If the character or substring is not found, it returns -1.

The syntax of the indexOf() method is as follows:

int indexOf(int ch)

Here, ch represents the character to be located within the string.

Let’s delve into an example to illustrate how to use the indexOf() method for checking if a string contains a specific character:

public class StringContainmentExample {
  public static void main(String[] args) {
    String str = "Hello, World!";
    char targetChar = 'o';

    int indexOfChar = str.indexOf(targetChar);

    if (indexOfChar != -1) {
      System.out.println(
          "String contains the character " + targetChar + " at index " + indexOfChar);
    } else {
      System.out.println("String does not contain the character " + targetChar);
    }
  }
}

Output:

String contains the character o at index 4

In this example, we initialize a string (str) and specify the target character (targetChar). The indexOf() method is then called on the string, passing targetChar as its parameter.

The result is stored in the variable indexOfChar.

A subsequent conditional check is performed: if indexOfChar is not equal to -1, indicating that the character was found, a message is printed with the character and its index. Otherwise, a message is printed to signify the absence of the character.

Similar to the previous method, indexOf() is also case-sensitive. This means that it distinguishes between uppercase and lowercase characters.

To perform a case-insensitive check, convert both the string and the target character to lowercase (or uppercase) using methods like toLowerCase() or toUpperCase() before applying the indexOf() method.

Here’s an example code snippet to demonstrate the case-sensitivity of the indexOf() method in Java:

public class CaseSensitivityExample {
  public static void main(String[] args) {
    String str = "Hello, World!";
    char targetUpperCaseChar = 'O';

    String strLower = str.toLowerCase();
    char targetLower = Character.toLowerCase(targetUpperCaseChar);
    int indexOfLower = strLower.indexOf(targetLower);

    if (indexOfLower != -1) {
      System.out.println("String contains the character " + targetUpperCaseChar
          + " (case-insensitive) at index " + indexOfLower);
    } else {
      System.out.println(
          "String does not contain the character " + targetUpperCaseChar + " (case-insensitive)");
    }
  }
}

Output:

String contains the character O (case-insensitive) at index 4

In this example, we have a similar string, str, and a target character, O. We demonstrate a case-insensitive check by converting both the string and the target character to lowercase using the toLowerCase() method before applying the indexOf() method.

Use the Enhanced for Loop to Check if a String Contains Character

The enhanced for loop, also known as the for-each loop, simplifies the process of iterating through arrays and collections in Java.

Its syntax is as follows:

for (elementType element : array) {
  // code to be executed for each element
}

In the context of checking string containment, we can leverage this loop to iterate through each character in the string.

Let’s dive into an example demonstrating how to use an enhanced for loop to check if a string contains a specific character:

public class StringContainmentExample {
  public static void main(String[] args) {
    String str = "Hello, World!";
    char targetChar = 'e';
    boolean containsChar = false;

    for (char c : str.toCharArray()) {
      if (c == targetChar) {
        containsChar = true;
        break;
      }
    }

    if (containsChar) {
      System.out.println("String contains the character " + targetChar);
    } else {
      System.out.println("String does not contain the character " + targetChar);
    }
  }
}

Output:

String contains the character e

In this example, we initialize a string (str) and specify the target character (targetChar). We also declare a boolean variable, containsChar, to keep track of whether the character is found during the iteration.

The enhanced for loop is employed to iterate through each character in the string. For each iteration, the loop compares the current character (c) with the target character (targetChar).

If a match is found, containsChar is set to true, and the loop is terminated using the break statement.

After the loop completes, a conditional check is performed based on the value of containsChar, and a corresponding message is printed.

Use Java Streams anyMatch() Method to Check if a String Contains a Character

Java Streams were introduced in Java 8 to facilitate functional-style programming on collections of elements. They allow for expressive and parallelizable operations on data, and their use can lead to more readable and concise code.

The anyMatch() method is a terminal operation in Java Streams, and it is used to check whether any elements of a stream match a given predicate. The syntax of the anyMatch() method is as follows:

boolean anyMatch(Predicate<? super T> predicate)

Here, Predicate<? super T> is a functional interface representing a predicate (a boolean-valued function) that takes an argument of type T (the type of the elements in the stream) or a supertype of T.

The anyMatch() method returns a boolean value, indicating whether an element of the stream matches the provided predicate. If at least one element satisfies the condition specified by the predicate, the result is true; otherwise, it returns false.

Let’s see an example to illustrate how this method can be used to check if a string contains a specific character:

import java.util.stream.IntStream;

public class StringContainmentExample {
  public static void main(String[] args) {
    String str = "Hello, World!";
    char targetChar = 'r';

    boolean containsChar = str.chars().anyMatch(c -> c == targetChar);

    if (containsChar) {
      System.out.println("String contains the character " + targetChar);
    } else {
      System.out.println("String does not contain the character " + targetChar);
    }
  }
}

Output:

String contains the character r

In this example, we use the chars() method on the string (str), which returns an IntStream of Unicode code points. We then utilize the anyMatch() terminal operation to check if any of the characters match the target character (targetChar).

The lambda expression (c -> c == targetChar) performs the comparison. In this case, it checks if any character in the string is equal to the target character.

After the stream operation, a boolean variable (containsChar) is set based on whether any match was found. A conditional check is then performed to print the appropriate message.

Use the matches() Method With Regular Expressions to Check if a String Contains Character

In Java, the matches() method, coupled with regular expressions (regex), provides another flexible way to check if a string contains a specific character.

The matches() method is a member of the String class in Java. It is used to check if a string matches a specified regular expression.

The method signature is as follows:

boolean matches(String regex)

Here, regex represents the regular expression against which the string is to be matched.

Let’s delve into an example to illustrate how the matches() method can be employed with a regex to check if a string contains a specific character:

public class StringContainmentExample {
  public static void main(String[] args) {
    String str = "Hello, World!";
    char targetChar = 'r';

    String regex = ".*" + targetChar + ".*";
    boolean containsChar = str.matches(regex);

    if (containsChar) {
      System.out.println("String contains the character " + targetChar);
    } else {
      System.out.println("String does not contain the character " + targetChar);
    }
  }
}

Output:

String contains the character r

In this example, we initialize a string (str) and specify the target character (targetChar). We then construct a regex pattern using the .* wildcard, which matches any sequence of characters before and after the target character.

The matches() method is invoked on the string, passing the constructed regex as its parameter. If the string matches the regex pattern, the result is true, indicating that the string contains the specified character.

A conditional check is then performed based on the value of containsChar, and a corresponding message is printed.

Conclusion

In Java, checking if a string contains a specific character is a common task with multiple solutions. The choice between methods depends on factors such as simplicity, performance, and the need for additional features like case-insensitivity or regular expression matching.

Understanding these methods equips us with a versatile toolkit for effective string manipulation in Java.

Related Article - Java String