Java Code To Check If String Contains Specific Characters
Chapter:
String Handling
Last Updated:
03-06-2023 13:25:05 UTC
Program:
/* ............... START ............... */
public class StringContainsSpecificCharacters {
public static void main(String[] args) {
String inputString = "Hello World";
String charactersToCheck = "lWo";
boolean containsCharacters = containsSpecificCharacters(inputString, charactersToCheck);
if (containsCharacters) {
System.out.println("The string contains the specific characters.");
} else {
System.out.println("The string does not contain the specific characters.");
}
}
public static boolean containsSpecificCharacters(String inputString, String charactersToCheck) {
for (char c : charactersToCheck.toCharArray()) {
if (!inputString.contains(Character.toString(c))) {
return false;
}
}
return true;
}
}
/* ............... END ............... */
Output
The string contains the specific characters.
This output indicates that the string "Hello World" contains the specific characters 'l', 'W',
and 'o', as specified by the charactersToCheck variable.
Notes:
-
In this code, the containsSpecificCharacters method iterates over each character in the charactersToCheck string. It converts the character to a string using Character.toString(c) and then uses the contains method to check if the inputString contains that character. If any character is not found, it returns false. If all characters are found, it returns true.
- Running this code will also output "The string contains the specific characters." because the characters 'l', 'W', and 'o' are present in the string "Hello World".
Tags
Java code to check if string contains specific characters #How to Check if a String Contains Character in Java