String.startsWith()
简述:
该函数用于判断当前字符串是否以指定的前缀开头。它调用了另一个重载的startsWith方法,传入前缀和起始索引0,检查前缀是否匹配字符串的开头部分。如果匹配,则返回true,否则返回false。
注意,如果前缀为空字符串或与当前字符串相等(通过equals方法比较),也会返回true。该方法自Java 1.0以来就存在。
源码:
public boolean startsWith(String prefix) {
return startsWith(prefix, 0);
}
实例:
public class Example {
public static void main(String[] args) {
String str = "Hello, World!";
// Check if the string starts with "Hello"
if (str.startsWith("Hello")) {
System.out.println("The string starts with 'Hello'");
} else {
System.out.println("The string does not start with 'Hello'");
}
}
}
上述示例代码演示了如何使用Java中String类的startsWith方法来检查一个字符串是否以指定的前缀开头。
在例子中,首先创建一个字符串"Hello, World!",然后使用startsWith方法检查该字符串是否以"Hello"开头。最后根据判断结果输出相应的信息。