String 常用方法
按功能分类介绍 String 的常用方法,方便查阅。
方法分类
| 分类 | 方法 |
|---|---|
| 长度 | length() |
| 查找 | indexOf(), contains() |
| 截取 | substring() |
| 转换 | toUpperCase(), toLowerCase() |
| 替换 | replace(), replaceAll() |
| 分割 | split() |
| 去除空白 | trim(), strip() |
长度和查找
java
String str = "Hello World";
// 长度
System.out.println("length: " + str.length());
// 查找
System.out.println("indexOf 'o': " + str.indexOf('o'));
System.out.println("lastIndexOf 'o': " + str.lastIndexOf('o'));
System.out.println("contains 'World': " + str.contains("World"));截取和分割
java
String str = "Hello,World,Java";
// 截取
System.out.println("substring(0,5): " + str.substring(0, 5));
System.out.println("substring(6): " + str.substring(6));
// 分割
String[] parts = str.split(",");
for (String part : parts) {
System.out.println(part);
}转换
java
String str = "Hello World";
// 大小写
System.out.println("toUpperCase: " + str.toUpperCase());
System.out.println("toLowerCase: " + str.toLowerCase());
// 替换
System.out.println("replace 'o' with '0': " + str.replace('o', '0'));
System.out.println("replaceAll regex: " + str.replaceAll("\\s+", "-"));
// 去空白
String withSpace = " Hello ";
System.out.println("trim: '" + withSpace.trim() + "'");
System.out.println("strip: '" + withSpace.strip() + "'");
// 拼接
System.out.println("concat: " + str.concat("!!!"));
// 判断
System.out.println("startsWith 'Hello': " + str.startsWith("Hello"));
System.out.println("endsWith 'World': " + str.endsWith("World"));注意事项
- 索引从 0 开始:小心越界
- substring:返回新字符串,原字符串不变
- split:注意特殊字符需要转义,如
.要写成\\. - JDK 11+:用
strip()替代trim(),能正确处理 Unicode 空白字符
