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
以提高效率。