Check if String Contains Any Character in Given Set in Java



In this article, we will learn to check if the string contains any character in the given set of characters in Java. We will iterate over the string and compare each character to a set of characters that we want to search for. If any match is found, the program will print the character and confirm that it is present in the string.

Problem Statement

Write a program in Java to check if the string contains any character in the given set of characters ?

Input

str = abcde
chSearch = 'b', 'c'

Output

Character b found in string abcde
Character c found in string abcde

Steps to check if the string contains any character

Following are the steps to check if the string contains any characters ?

  • First, define a string, such as "abcde".
  • Create an array of characters that you want to search for within the string, such as {'b', 'c'}.
  • Loop through each character of the string using a for loop.
  • Inside this loop, iterate over the set of characters to be searched, comparing each character with the current character of the string.
  • If a match is found, print a message indicating the character and confirming that it is present in the string.

Java program to check if the string contains any character

The following is an example to check if the string contains any characters ?

public class Demo {
   public static void main(String[] args) {
      String str = "abcde";
      // set of characters to be searched
      char[] chSearch = {'b', 'c'};
      for (int i = 0; i < str.length(); i++) {
         char ch = str.charAt(i);
         for (int j = 0; j < chSearch.length; j++) {
            if (chSearch[j] == ch) {
               System.out.println("Character "+chSearch[j]+" found in string "+str);
            }
         }
      }
   }
}

Output

Character b found in string abcde
Character c found in string abcde

Time complexityO(n * m)

Space complexityO(1)

Code Explanation

The above program defines a string (str) and a set of characters (chSearch) to search for. It uses two nested for loops: we can see that the outer loop iterates through each character in the string, and the inner loop checks each character in the search set. If a match is found, it prints a message saying that the character was found in the string. The message includes both the found character and the string in which it was found.

Updated on: 2024-10-15T11:53:07+05:30

898 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements