String類 字串的生成和關於字串的常用方法總結
阿新 • • 發佈:2021-01-25
String類 字串的生成和關於字串的常用方法總結
一、字串的特點:
- 字串的內容永不可變
- 正因為字串不可改變,所以字串師可以共享使用的。
- 字串效果上相當於char[ ] 字元陣列,但是底層原理師byte[ ]位元組陣列。
- 對於字串是引用型別,使用 == 是進行地址值的比較,內容比較應該使用equals()
二、字串的生成方法
三種構造方法和一種直接建立
- pubic String(),建立一個空白字串
- public String(char [ ] arr),根據字元陣列的內容來建立對應的字串
- public String(byte[ ] arr ),根據位元組陣列的內容,來建立對應的字串
- String str = “ ”;直接建立;
public static void main(String[] args) {
// pubic String(),建立一個空白字串
String str1 = new String();
// public String(char [ ] arr),根據字元陣列的內容來建立對應的字串
char[] c = {'c','b','a'};
String str2 = new String(c);
// public String(byte[ ] arr ),根據位元組陣列的內容,來建立對應的字串
byte[] b = {97,98,99};
String str3 = new String(b);
// String str4 = "bca"; 直接建立
String str4 = "bca";
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);
}
三、常用的相關方法
返回型別 | 方法 |
---|---|
int | length() |
String | concat(String str) |
char | charAt(int index) |
int | indexof(String str) |
- length() 獲取字串中含有字元個數,拿到字串的長度。
- concat(String str) 將兩個字串拼接成新的字串。
- chatAt(int index) 獲取指定索引位置的單個字元。
- indexOf(String str)
public static void main(String[] args) {
//獲取字串的長度
String str = "flakjflkaj";
System.out.println("字串的長度:"+str.length());//10
//拼接字串
String str1 = "Hello";
String str2 = "World";
String str3 = str1.concat(str2);//HelloWorld
System.out.println(str3);
System.out.println("+++++++++");
//獲取指定索引位置的單個字元
char c = str1.charAt(1);
System.out.println("在1號索引位置的字元是:"+c);//e
System.out.println("==========");
//查詢引數字串在本來字串當中出現的第一次索引位置
//如果根本沒有,返回-1值
int index = str3.indexOf("llo");
System.out.println(index);//2
}