Open In App

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

Last Updated : 06 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

  • By using the startsWith() method from the String class

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




// 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:

  • In the above program, first we have taken one String value that is HelloWorld.
  • Then we took some prefixes as a String array.
  • After that, we have taken one boolean value for checking if a string starts with one of several prefixes or not.
  • If started, then boolean become true otherwise become false.
  • After that compare the String value with prefixes in the array.
  • Finally print the required result.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads