Java startsWith() Method: Usage and Examples

The startsWith() method in Java is used to check if a string begins with a specified prefix. It takes a string parameter as the prefix and returns a boolean value indicating whether the current string starts with that prefix.

原文:我很高兴能帮助您。
重述:I am glad to be able to help you.

String str = "Hello, World!";
boolean startsWithHello = str.startsWith("Hello");
System.out.println(startsWithHello); // 输出 true

boolean startsWithHi = str.startsWith("Hi");
System.out.println(startsWithHi); // 输出 false

The startsWith() method is case-sensitive when comparing strings at the beginning. To ignore case, you can use another version of the startsWith() method by passing in a flag to ignore case.

String str = "Hello, World!";
boolean startsWithHelloIgnoreCase = str.startsWith("hello", 0);
System.out.println(startsWithHelloIgnoreCase); // 输出 true
bannerAds