
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If a String Contains Only Certain Characters in Java
For a given string, say "str", write a Java program to check if it contains each character from a specified character array. If it contains print "found" otherwise "not found".
A String in Java is a class that represents a contiguous block of characters.
Example Scenario:
Input 1: String str = "pqrst"; Input 2: char[] chSearch = {'p', 'q', r'}; Output: res = Character p, q and r found in given string
In the string "pqrst", we are searching for the character set {'p', 'q', r'}.
Using Iteration
Here, use for loop to iterate till the length of the string and check every character in the string. If the matching character from the given character array is found in the string, then it would be a success otherwise not.
Example
The following Java program illustrates how to check if the specified string contains certain characters.
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 of the above code is as follows ?
Character p found in string pqrst Character q found in string pqrst Character r found in string pqrst
Using Java Streams
Java Streams are introduced with the release of Java 8. It is used to perform various operations like filtering, mapping and reducing on Java collections and arrays. Here, we use the filter() method to find only those characters from the stream that are present in the character array.
Example
Let's see the practical demonstration of the above approach ?
import java.util.Arrays; public class Demo { public static void main(String[] args) { String str = "pqrst"; // characters to be searched char[] chSearch = {'p', 'q', 'r'}; // convert the string to a stream of characters str.chars() // convert each character to a char .mapToObj(c -> (char) c) // filter characters that are in chSearch .filter(ch -> new String(chSearch).indexOf(ch) >= 0) // for each matching character, print the message .forEach(ch -> System.out.println("Character " + ch + " found in string " + str)); } }
Following output will be displayed on running the above code ?
Character p found in string pqrst Character q found in string pqrst Character r found in string pqrst