Java Program to check if the String contains only certain characters

Java 8Object Oriented ProgrammingProgramming

The following is our string.

String str = "pqrst";

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

// set of characters to be searched
char[] chSearch = {'p', 'q', r'};

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 a success.

The following is an example.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String str = "pqrst";
      // characters to be searched
      char[] chSearch = {'p', 'q', 'r'};
      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 p found in string pqrst
Character q found in string pqrst
Character r found in string pqrst
raja
Published on 17-Dec-2018 06:24:14
Advertisements