Java 中String类的常用方法
Java 中的 String
类提供了丰富的方法用于字符串操作,以下是最常用的一些方法分类总结:
一、获取字符串信息
-
length()
:返回字符串长度(字符个数)String s = "hello"; int len = s.length(); // len = 5
-
charAt(int index)
:返回指定索引(从0开始)的字符char c = "hello".charAt(1); // c = 'e'
-
indexOf(String str)
:返回子串str
首次出现的索引,未找到返回-1
int idx = "hello world".indexOf("lo"); // idx = 3
-
lastIndexOf(String str)
:返回子串str
最后出现的索引int idx = "ababa".lastIndexOf("aba"); // idx = 2
二、字符串比较
-
equals(Object obj)
:判断两个字符串内容是否完全相同(区分大小写)"abc".equals("ABC"); // false
-
equalsIgnoreCase(String str)
:忽略大小写比较内容"abc".equalsIgnoreCase("ABC"); // true
-
compareTo(String str)
:按字典顺序比较,返回差值(正数:当前串大;负数:参数串大;0:相等)"apple".compareTo("banana"); // 负数('a' < 'b')
三、字符串截取与拆分
-
substring(int beginIndex)
:从beginIndex
截取到末尾"hello".substring(2); // "llo"
-
substring(int beginIndex, int endIndex)
:截取[beginIndex, endIndex)
范围的子串(左闭右开)"hello".substring(1, 4); // "ell"
-
split(String regex)
:按正则表达式拆分字符串,返回字符串数组String[] parts = "a,b,c".split(","); // ["a", "b", "c"]
四、字符串修改(注意:String 是不可变的,以下方法返回新字符串)
-
toLowerCase()
/toUpperCase()
:转为全小写 / 全大写"Hello".toLowerCase(); // "hello" "Hello".toUpperCase(); // "HELLO"
-
trim()
:去除首尾空白字符(空格、换行、制表符等)" hello ".trim(); // "hello"
-
replace(char oldChar, char newChar)
:替换所有指定字符"hello".replace('l', 'x'); // "hexxo"
-
replace(String oldStr, String newStr)
:替换所有指定子串"hello world".replace("world", "java"); // "hello java"
-
concat(String str)
:拼接字符串(等价于+
运算符)"hello".concat(" world"); // "hello world"
五、判断字符串特性
-
startsWith(String prefix)
:判断是否以指定前缀开头"hello".startsWith("he"); // true
-
endsWith(String suffix)
:判断是否以指定后缀结尾"hello.txt".endsWith(".txt"); // true
-
isEmpty()
:判断字符串是否为空(长度为0)"".isEmpty(); // true "a".isEmpty(); // false
-
contains(CharSequence s)
:判断是否包含指定子串"hello".contains("ll"); // true
六、其他常用方法
-
toCharArray()
:将字符串转为字符数组char[] arr = "hello".toCharArray(); // ['h','e','l','l','o']
-
valueOf(xxx)
:静态方法,将其他类型转为字符串(常用)String.valueOf(123); // "123" String.valueOf(true); // "true"
-
format(String format, Object... args)
:静态方法,格式化字符串(类似printf
)String.format("Name: %s, Age: %d", "Tom", 20); // "Name: Tom, Age: 20"
注意事项
String
是不可变对象,所有修改方法都会返回新的字符串,原字符串不变。- 频繁修改字符串时,建议使用
StringBuilder
或StringBuffer
以提高效率。