How do I check a string starts with a specific word?

To test if a string starts with a specific prefix we can use the String.startsWith(String prefix) method. This method returns a boolean true as the result if the string starts with that specified prefix. The String.startsWith() method checks the prefix in case-sensitive manner.

The following code snippet give us a small example how to use this method, but instead of just straightly checks using the startsWith() method, we add a scanner that allows us to input the prefix that we want to test.

package org.kodejava.lang;

import java.util.Scanner;

import static java.lang.System.in;

public class StringStartsWithExample {
    private static final Scanner scanner = new Scanner(in);

    public static void main(String[] args) {
        String text = "The quick brown fox jumps over the lazy dog";
        System.out.println("Text: " + text);

        System.out.print("Type the prefix to test: ");
        String search = scanner.nextLine();

        // Check if the text start with the search text.
        if (text.startsWith(search)) {
            System.out.println("Yes, the fox is the quick one");
        } else {
            System.out.println("The fox is a slow fox");
        }
    }
}

The code snippet print the following output:

Text: The quick brown fox jumps over the lazy dog
Type the prefix to test: The quick brown fox
Yes, the fox is the quick one
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.