Java:String.startsWith 方法

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 方法在处理用户输入或配置文件时非常有用,但需注意大小写敏感性。

相关推荐
萧瑟余晖4 分钟前
JDK 26 新特性详解
java·开发语言
马优晨39 分钟前
Freemarker 完整讲解(后端 Java 模板引擎)
java·开发语言·freemarker·freemarker 完整讲解·freemarker模板引擎
人邮异步社区2 小时前
怎么把C语言学到精通?
c语言·开发语言
心平气和量大福大3 小时前
C#-WPF-控件-TextBox 数据绑定
开发语言·c#·wpf
ttwuai3 小时前
Cursor 生成 CRUD 后,Go 后台接口别只测 200:JWT、RBAC 和 tenant_id 怎么验
开发语言·后端·golang
维天说3 小时前
CLI-Switch 2026年3月版历史设计:Hook、TTY 隔离与 JSON 状态
java·服务器·json
এ慕ོ冬℘゜3 小时前
前端基础:什么是时间戳?JS获取时间戳三种方法与实战用途
开发语言·前端·javascript
执明wa4 小时前
LayoutInflater详解: XML是如何变成View的?
android·xml·开发语言·android studio
一次旅行4 小时前
Python+大模型端到端自动化日报系统
开发语言·python·自动化
Zane19944 小时前
并发 vs 并行:别再傻傻分不清了,一文讲透 Java 并发编程的第一课
java·后端