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
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024