Java筆記——String類
阿新 • • 發佈:2021-01-20
String
- String的建立
//方法一
String str1 = "hello";
//方法二
String str2 = new String("hello");
//方法三
char[] arr = {'a','b','c'};
String str3 = new String(arr);
- 字串比較
a. 比較相等
.equal
==
- String 使用 == 比較的不是兩個字串的內容,而是比較兩個引用是否是指向同一個物件;
b. 比較大小
按照字典序判斷大小:
- 先比較首個字元的大小(看字元的Unicode的值的大小)
- 如果首個字元能分出大小關係,兩個字串的大小就確定了
- 如果首個字元不能區分出大小,則繼續比較下一個字元
例如:
" abbcc " 和 " za " 相比 ,za 比 abbcc 大;
compareTo的用法:
public class Test01 {
public static void main(String[] args) {
String a = "hello";
String b = "hallo";
// compareTo 返回的是一個int 值
// 若 a 比 b 大 ,則返回 >0 的結果
// 若 a 比 b 小 ,則返回 <0 的結果
// 若 a 和 b 相等 ,則返回 0 的結果
int result = a.compareTo(b);
System.out.println(result);
}
}
結果:
注意:
這裡的返回結果不是 -1 / +1 ;
返回的字元為兩個字元ASCII碼值的差值(不一定,JDK不同計算結果不同)
c. 不區分大小寫比較
- compareToIgnoreCase( )
- euqalsIgnoreCase( )
- 字串常量池
可以使用String的intern 方法來手動吧String物件加入到字串常量池中:
public class Test01 {
public static void main(String[] args) {
String a = "hello";
String b = new String("hello");
String c = new String("hello").intern();
System.out.println(a == b);
System.out.println(a == c);
}
}
結果:
- 字串常見操作
- 字串比較
equals( ) :
public class Test01 {
public static void main(String[] args) {
String a = "hello";
String b = "hallo";
System.out.println(a.equals(b));
}
}
結果:
compareTo( ) : 見第2條字串比較
- 字串查詢
indexOf( ) :
public class Test01 {
public static void main(String[] args) {
String a = "hello";
String b = "ll";
//返回下標若查詢不到則返回-1
System.out.println(a.indexOf(b));
}
}
結果:
補充:
- lastIndexOf ( ) : 從後往前找
- startWith( ) :判斷是否以 … 開始
- endsWith( ) :判斷是否以… 結束
- 字串替換
replace( ) :
public class Test01 {
public static void main(String[] args) {
String a = "hello happy hair";
System.out.println(a.replace("h","H"));
}
}
結果:
- replaceAll( ) : 替換所有的指定內容
- replaceFirst( ) : 替換首個內容
- 字串拆分
split( ) :
public class Test01 {
public static void main(String[] args) {
String a = "i,am,learning,now";
String[] result = a.split(",");
for (String s : result){
System.out.printf( s +" ");
}
}
}
結果:
- split( String regex) : 將字串全部拆分
- split( String regex, int limit) : 將字串部分拆分,該陣列長度就是 limit 極限
- 字串擷取
substring( ) :
public class Test01 {
public static void main(String[] args) {
String a = "helloworld";
System.out.println(a.substring(5));
System.out.println(a.substring(0,5));
}
}
結果:
- substring( int beginIndex ): 從指定索引擷取到結尾
- substring( int beginIndex, int endIndex) : 擷取部分內容
- StringBuffer 和 StringBuilder
由於String的不可修改性,為了方便字串的修改,提供了 StringBuffer類 和 StringBuilder類。
- String & StringBuffer & StringBuilder 的區別:
- String的內容不可修改, StringBuffer 和StringBuilder 的內容可以修改;
- StringBuffer 和 StringBuilder 大部分功能相似;
- StringBuffer 採用同步處理,屬於執行緒安全操作 ;StringBuilder 沒有采用同步處理,因此屬於執行緒不安全操作;