How to check if a string starts with one of several prefixes in java?

How to check if a string starts with one of several prefixes in java?

To check if a string starts with one of several prefixes in Java, you can use the startsWith() method in combination with logical OR (||) or the Stream API. Here are two common approaches:

Using Logical OR (||):

You can use the startsWith() method multiple times, each time checking for a different prefix, and combine the checks using || (logical OR).

String input = "Hello, world!"; String[] prefixes = {"Hello", "Hi", "Hey"}; boolean startsWithPrefix = false; for (String prefix : prefixes) { if (input.startsWith(prefix)) { startsWithPrefix = true; break; // Exit the loop early if a match is found } } if (startsWithPrefix) { System.out.println("Input starts with one of the prefixes."); } else { System.out.println("Input does not start with any of the prefixes."); } 

Using Stream API (Java 8 and later):

If you're using Java 8 or later, you can use the Stream API to achieve the same result in a more concise way:

import java.util.Arrays; String input = "Hello, world!"; String[] prefixes = {"Hello", "Hi", "Hey"}; boolean startsWithPrefix = Arrays.stream(prefixes).anyMatch(input::startsWith); if (startsWithPrefix) { System.out.println("Input starts with one of the prefixes."); } else { System.out.println("Input does not start with any of the prefixes."); } 

In this approach, Arrays.stream(prefixes) creates a stream of prefixes, and anyMatch(input::startsWith) checks if any of the prefixes match the input string's beginning.

Both of these methods allow you to check if a string starts with one of several prefixes efficiently and provide flexibility when dealing with multiple possible prefixes.


More Tags

python-turtle azure-servicebus-queues refresher derivative file-format console slack-api android-notifications forms jquery-effects

More Java Questions

More Stoichiometry Calculators

More Investment Calculators

More Animal pregnancy Calculators

More Statistics Calculators