Java Program to check if the String contains any character in the given set of characters

Java 8Object Oriented ProgrammingProgramming

Here, we have a string.

String str = "abcde";

In the above string, we want to search for the following set of characters.

// set of characters to be searched
char[] chSearch = {'b', 'c'};

For this, loop through the length of the string and check every character in the string str. If the matching character from “chSearch” is found in the string, then it would be success.

The following is an example.

Example

 Live Demo

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
raja
Published on 17-Dec-2018 10:48:42
Advertisements