Java:startsWith()
startsWith() 是 Java 中 String 类的一个方法,用于检查字符串是否以指定的前缀开始。该方法有两种重载形式,能够满足不同的匹配需求。
1、方法定义
单参数形式:boolean startsWith(String prefix)
检查整个字符串是否以指定的前缀开始。
双参数形式:boolean startsWith(String prefix, int toffset)
从指定的索引位置(索引位置从0开始)开始检查字符串是否以指定的前缀开始。
2、使用示例
public class StartsWithExample {
public static void main(String[] args) {
String str = "hello world";
// 检查字符串是否以 "hel" 开始
boolean startsWithHel = str.startsWith("hel");
System.out.println("字符串是否以 'hel' 开始:" + startsWithHel); // 输出 true
// 检查字符串是否以 "world" 开始
boolean startsWithWorld = str.startsWith("world");
System.out.println("字符串是否以 'world' 开始:" + startsWithWorld); // 输出 false
// 从指定位置开始检查
boolean startsWithWorldAt7 = str.startsWith("world", 6);
System.out.println("从索引6开始是否以 'world' 开始:" + startsWithWorldAt7); // 输出 true
}
}
运行结果说明
str.startsWith("hel")返回true,因为字符串确实以 "hel" 开头str.startsWith("world")返回false,因为整个字符串不以 "world" 开头str.startsWith("world", 6)返回true,因为从索引位置6开始的子字符串以 "world" 开头
与其他方法的区别
与 JavaScript 中的类似方法相比,Java 的 startsWith() 功能更为专注,专门用于检查字符串前缀,而 indexOf() 方法用于查找子字符串的位置,返回的是索引值而非布尔值。
该方法在实际编程中常用于文件名检查、URL 协议验证、命令识别等场景。
