Java Program to check if the String contains only certain characters


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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 27-Jun-2020

864 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements