Java提供了多種工具和類來處理字串,其中最常用的是String類,還有StringBuilder和StringBuffer來應對特定情況下的字串操作需求
String 類的基本操作
1.字串比較
equals() 方法:比較兩個字串的內容是否相同。
equalsIgnoreCase() 方法:忽略大小寫進行比較。
compareTo() 方法:按字典順序比較兩個字串,返回整數值(負數、零、正數)。
2.字串串接
concat() 方法:將兩個字串連接起來。
+操作符:常用的字串串接方式。
3.字串切割
split() 方法:根據指定的分隔符將字串切割成字串陣列。
4.字串長度
length() 方法:返回字串的長度(字元數)。
eg.
String str = "Hello World";
System.out.println("Length: " + str.length()); // 11
5.取得字串中的字元
charAt() 方法:取得字串中指定索引位置的字元。
eg.
String str = "Hello";
char ch = str.charAt(1); // 'e'
6.搜尋字串
indexOf() 方法:搜尋字串中指定字元或子字串的位置,返回其索引(第一個匹配的)。
lastIndexOf() 方法:從後向前搜尋字串,返回最後一個匹配的索引。
7.取子字串
substring() 方法:從字串中擷取指定範圍的子字串。
eg.
String str = "Hello World";
String subStr = str.substring(0, 5); // "Hello"
8.字串替換
replace() 方法:替換字串中的指定字元或子字串。
eg.
String str = "Hello World";
String replacedStr = str.replace("World", "Java"); // "Hello Java"