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

Similar Programs Chapter Last Updated
How To Check If A String Contains A Particular Substring In Java String Handling 22-08-2023
How To Split A String Into Substrings in Java String Handling 22-08-2023
How To Remove A Substring From A String Java String Handling 22-08-2023
Java Program To Remove Repeated Characters In A String String Handling 15-08-2023
How To Count The Number Of Cccurrences Of Each Character In A String In Java String Handling 03-06-2023
Java Program To Replace A Character In A String String Handling 03-06-2023
Java Program To Split A String String Handling 03-06-2023
String Length Implementation Java String Handling 02-12-2019

1