Java中的String类是用来表示字符串的不可变类,日常开发中几乎所有文本相关的处理都要依赖它的方法。掌握String类的常用方法能大幅降低字符串处理的复杂度,提升代码编写效率。

String类常用核心方法分类
字符串判断相关方法
这类方法主要用于判断字符串的状态或内容是否符合预期,返回值为布尔类型。
- equals(Object obj):判断当前字符串与指定对象的内容是否相等,区分大小写。
- equalsIgnoreCase(String anotherString):判断字符串内容是否相等,不区分大小写。
- startsWith(String prefix):判断字符串是否以指定前缀开头。
- endsWith(String suffix):判断字符串是否以指定后缀结尾。
- contains(CharSequence s):判断字符串是否包含指定的字符序列。
- isEmpty():判断字符串是否为空字符串,即长度为0。
下面是判断类方法的使用示例:
public class StringCheckDemo {
public static void main(String[] args) {
String str1 = "HelloWorld";
String str2 = "helloworld";
// 区分大小写判断相等
System.out.println(str1.equals(str2)); // 输出false
// 不区分大小写判断相等
System.out.println(str1.equalsIgnoreCase(str2)); // 输出true
// 判断前缀
System.out.println(str1.startsWith("Hello")); // 输出true
// 判断后缀
System.out.println(str1.endsWith("World")); // 输出true
// 判断是否包含指定内容
System.out.println(str1.contains("loWo")); // 输出true
// 判断是否为空
String emptyStr = "";
System.out.println(emptyStr.isEmpty()); // 输出true
}
}
字符串获取相关方法
这类方法用于获取字符串的长度、指定位置的字符或子串等内容。
- length():返回字符串的长度,即字符的个数。
- charAt(int index):返回字符串中指定索引位置的字符,索引从0开始。
- indexOf(String str):返回指定子串在当前字符串中第一次出现的索引位置,不存在则返回-1。
- lastIndexOf(String str):返回指定子串在当前字符串中最后一次出现的索引位置,不存在则返回-1。
- substring(int beginIndex):截取从指定索引开始到字符串末尾的子串。
- substring(int beginIndex, int endIndex):截取从beginIndex到endIndex-1位置的子串,包含开始位置不包含结束位置。
获取类方法的使用示例如下:
public class StringGetDemo {
public static void main(String[] args) {
String str = "Java字符串处理实战";
// 获取字符串长度
System.out.println(str.length()); // 输出10
// 获取指定位置的字符
System.out.println(str.charAt(2)); // 输出字
// 获取子串第一次出现的位置
System.out.println(str.indexOf("字符串")); // 输出2
// 获取子串最后一次出现的位置
System.out.println(str.lastIndexOf("实")); // 输出8
// 截取子串(从索引4开始)
System.out.println(str.substring(4)); // 输出串处理实战
// 截取指定范围的子串
System.out.println(str.substring(2, 5)); // 输出字符串
}
}
字符串转换相关方法
这类方法用于实现字符串和其他数据类型、其他字符串之间的转换。
- toCharArray():将字符串转换为字符数组。
- valueOf(参数):静态方法,将基本数据类型、对象等转换为字符串。
- toLowerCase():将字符串中的所有字符转换为小写。
- toUpperCase():将字符串中的所有字符转换为大写。
- concat(String str):将指定字符串拼接到当前字符串末尾,等价于使用+拼接。
- replace(CharSequence oldChar, CharSequence newChar):将字符串中所有的oldChar替换为newChar。
转换类方法的使用示例如下:
public class StringConvertDemo {
public static void main(String[] args) {
String str = "AbCdEfG";
// 转换为字符数组
char[] charArray = str.toCharArray();
System.out.println(charArray[2]); // 输出C
// 基本类型转字符串
int num = 123;
String numStr = String.valueOf(num);
System.out.println(numStr); // 输出123
// 转换为小写
System.out.println(str.toLowerCase()); // 输出abcdefg
// 转换为大写
System.out.println(str.toUpperCase()); // 输出ABCDEFG
// 拼接字符串
String newStr = str.concat("123");
System.out.println(newStr); // 输出AbCdEfG123
// 替换字符串内容
System.out.println(str.replace("Cd", "XX")); // 输出AbXXEfG
}
}
字符串处理其他常用方法
除了上述分类的方法外,还有几个高频使用的字符串处理方法。
- trim():去除字符串首尾的空白字符,中间的空白不会去除。
- split(String regex):按照指定的正则表达式将字符串分割为字符串数组。
- matches(String regex):判断字符串是否符合指定的正则表达式规则。
- intern():返回字符串在字符串常量池中的引用,若常量池不存在则先存入再返回。
其他常用方法的使用示例如下:
public class StringOtherDemo {
public static void main(String[] args) {
String str1 = " hello world ";
// 去除首尾空白
System.out.println(str1.trim()); // 输出hello world
String str2 = "张三,李四,王五";
// 分割字符串
String[] names = str2.split(",");
for (String name : names) {
System.out.println(name);
}
// 输出张三 李四 王五
String phone = "13812345678";
// 判断是否符合手机号正则规则
System.out.println(phone.matches("^1[3-9]\d{9}$")); // 输出true
}
}
字符串处理实战技巧
避免频繁使用+拼接字符串
由于String是不可变类,每次使用+拼接字符串都会生成新的String对象,在循环中使用+拼接会造成大量对象创建,影响性能。如果是循环拼接或者大量拼接场景,建议使用StringBuilder或StringBuffer类。
错误示例:
public class BadConcatDemo {
public static void main(String[] args) {
String result = "";
for (int i = 0; i < 10000; i++) {
// 每次循环都会创建新的String对象,性能差
result += i;
}
System.out.println(result);
}
}
优化后的示例:
public class GoodConcatDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++) {
sb.append(i);
}
String result = sb.toString();
System.out.println(result);
}
}
字符串比较尽量使用equals方法
很多初学者会用==判断字符串是否相等,==判断的是两个字符串对象的引用地址是否相同,而不是内容。只有字符串常量池中的相同字符串才会引用地址相同,所以内容比较必须使用equals方法。
public class StringCompareDemo {
public static void main(String[] args) {
String s1 = "hello";
String s2 = new String("hello");
// ==判断引用地址,结果为false
System.out.println(s1 == s2);
// equals判断内容,结果为true
System.out.println(s1.equals(s2));
}
}
合理使用intern方法减少内存占用
当我们需要创建大量重复内容的字符串时,可以使用intern方法,让所有相同内容的字符串引用常量池中的同一个对象,减少内存占用。比如从文件或数据库读取大量重复的字符串内容时,就可以使用这个方法优化。
public class InternDemo {
public static void main(String[] args) {
String s1 = new String("test").intern();
String s2 = new String("test").intern();
// 经过intern处理后,引用地址相同,结果为true
System.out.println(s1 == s2);
}
}
注意事项
需要注意的是String类是不可变的,所有对字符串的修改操作都会返回一个新的字符串对象,原字符串不会发生改变。如果需要对字符串做大量修改操作,优先考虑使用StringBuilder,多线程场景下使用StringBuffer保证线程安全。