1、基本用法
startsWith 是 Java String 类的一个方法,用于检查字符串是否以指定的前缀开始。该方法有两种重载形式:
boolean startsWith(String prefix):检查整个字符串是否以指定的前缀开始。
boolean startsWith(String prefix, int toffset):从指定的索引位置开始检查字符串是否以指定的前缀开始。
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
}
}
3、关键点说明
区分大小写:startsWith 方法区分大小写,例如 "Hello".startsWith("hello") 返回 false。
性能优化:由于 String 是不可变的,startsWith 方法的实现效率较高,通常只需比较前缀长度的字符。
与其他方法的区别:与 indexOf 方法不同,startsWith 返回布尔值而非索引值,专门用于前缀检查。
4、实际应用
public class Test {
public static void main(String[] args) {
String url = "https://www.example.com";
// 检查 URL 是否以 "https" 开头
if (url.startsWith("https")) {
System.out.println("这是一个安全的 HTTPS 连接");
} else {
System.out.println("这不是一个安全的连接");
}
}
}
注意:startsWith 方法在处理用户输入或配置文件时非常有用,但需注意大小写敏感性。