Open In App

How to Check if a String Starts With One of Several Prefixes in Java?

Java programming provides a lot of packages for solving real-time problems. In our case, we need to check if a given string starts with one of several prefixes. For This first, we need to take one String value after that take some prefixes for testing if the String starts with one of several prefixes or not.

Approach

To check if a string starts with one of several prefixes, we have one basic solution listed below.



This is a basic solution to our problem. Now we will see each of them with Java examples to get the concept in a better way. For this, we need to take some prefixes and one String value as input.

Program to Check if a String Starts with One of Several Prefixes in Java

startsWith() method is available in the String class, this method can check if the given String starts with already taken prefixes as a String array. By using a for loop, we will check the String with every value in the Prefix array. If matches then we print as matched otherwise print not matched.



Syntax:

inputString.startsWith(prefix)

Example:

We can get more clarity by observing the below Java example:




// Java program to check if a string starts with one of several prefixes using startsWith()
  
public class StringPrefixCheck 
{
    public static void main(String[] args) 
    {
        String inputString = "HelloWorld";
        String[] prefixes = {"Hello", "Hi", "Hey"};
  
        boolean startsWithPrefix = false;
  
        for (String prefix : prefixes) 
        {
            if (inputString.startsWith(prefix)) 
            {
                startsWithPrefix = true;
                break;
            }
        }
  
        if (startsWithPrefix) 
        {
            System.out.println("The string starts with one of the prefixes.");
        } else {
            System.out.println("The string does not start with any of the prefixes.");
        }
    }
}

Output
The string starts with one of the prefixes.


Explanation of the Program:


Article Tags :