??博客主頁:愛敲代碼的小楊.
?專欄:《Java SE語法》
??感謝大家點贊????收藏?評論???,您的三連就是我持續(xù)更新的動力??
前言
在程序開發(fā)中經(jīng)常會用到字符串。字符串是指一連串的字符,它是由許多單個字符連接而成的,如多個英文字母所組成的英文單詞。字符串可以包含任意字符,這些字符必須包含在一對雙引號""之內(nèi),例如:“abc”。Java定義了3個封裝字符串的類,分別是String
類、StringBuffer
類和StringBulider
類。它們位于java.lang
包中,并提供了一系列操作字符串的方法,這些方法不需要導(dǎo)包就可以直接使用。下面將對String
類、StringBuffer
類和StringBulider
類進(jìn)行講解。
1. String類
1.1 字符串的構(gòu)造
String
類提供了構(gòu)造方法非常多,常用的就以下三種:
public class Main {
public static void main(String[] args) {
// 使用常量串構(gòu)造
String s1 = "hello";
System.out.println(s1);
// 直接new String對象
String s2 = new String("hello");
System.out.println(s2);
// 使用字符數(shù)組進(jìn)行構(gòu)造
char[] chars = {'h','e','l','l','o'};
String s3 = new String(chars);
System.out.println(s3);
}
}
其他方法需要用到時,大家參考Java在線文檔:String官方文檔
【注意】:
-
String是引用類型,內(nèi)部并不存儲字符串本身,在String類的實現(xiàn)源碼中,String類實例變量如下:
public class Main { public static void main(String[] args) { // s1和s2引用的是不同對象 s1和s3引用的是同一對象 String s1 = new String("hello"); String s2 = new String("world"); String s3 = s1; // s3這個引用指向了s1這個引用的對象 System.out.println(s3); // hello System.out.println(s1.length());// 獲取字符串的長度 System.out.println(s1.isEmpty());// 如果字符串長度為0,返回true,否則返回false String s4 = ""; System.out.println(s4.length()); // 0 System.out.println(s4.isEmpty());// true }
內(nèi)存圖:
-
在Java中""引起來的也是String類型對象
// 打印"hello"字符串(String對象)的長度 System.out.println("hello".length());// 5
1.2 String對象的比較
字符串的比較是常見操作之一,比如:字符串排序。Java中總共提供了4種方式:
1. ==比較是否引用同一個對象
注意:對于內(nèi)置類型,==
比較的是變量中的值;對于引用類型==
比較的是引用中的地址。
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = 10;
// 對于基本類型變量,==比較兩個變量中存儲的值是否相同
System.out.println(a == b); // false
System.out.println(a == c); // true
// 對于引用類型變量,==比較兩個引用變量引用的是否為同一個對象
String s1 = new String("hello");
String s2 = new String("hello");
String s3 = new String("world");
String s4 = s1;
System.out.println(s1 == s2); // false
System.out.println(s2 == s3); // false
System.out.println(s1 == s4); // true
}
}
2. equals()方法:按照字典序比較
字典序:字符大小的順序
String
類重寫了父類Object
中equals
方法,Object
中equals
默認(rèn)按照==
比較,String
重寫equals
方法后,按照 如下規(guī)則進(jìn)行比較,比如:s1.equals(s2)
public class Main {
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = new String("hello");
String s3 = new String("Hello");
// s1、s2、s3引用的是三個不同對象,因此==比較結(jié)果全部為false
System.out.println(s1 == s2); // false
System.out.println(s1 == s3); // false
// equals比較:String對象中的逐個字符
// 雖然s1與s2引用的不是同一個對象,但是兩個對象中放置的內(nèi)容相同,因此輸出true
// s1與s3引用的不是同一個對象,而且兩個對象中內(nèi)容也不同,因此輸出false
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); // false
}
}
【注意】:為什么以下代碼輸出的結(jié)果都是true
?
答:因為在 Java 中有一塊特殊的內(nèi)存(常量池),存儲在堆上。
它的作用是什么呢?
- 只要是""雙引號括起來的字符串存放在這里。
- 存儲字符串之前它會找常量池里是否存在這個字符串,如果有就不存放了(常量池不會重復(fù)存放相同的值),所以上述代碼中
s1
和s2
都指向常量池hello
的地址。
3. compareTo()方法: 按照字典序進(jìn)行比較
與equals
不同的是,equals
返回的是boolean
類型,而compareTo
返回的是int類型。具體比較方式:
- 先按照字典次序大小比較,如果出現(xiàn)不等的字符,直接返回這兩個字符的大小差值
- 如果前k個字符相等(k為兩個字符長度最小值),返回值兩個字符串長度差值
public class Main {
public static void main(String[] args) {
String s1 = new String("abc");
String s2 = new String("ac");
String s3 = new String("abc");
String s4 = new String("abcdef");
// s1 和 s2 比較大小 s1 > s2 返回大于0的數(shù)字 s1 < s2 返回小于0的數(shù)字 否則返回0
// 返回差值就是對應(yīng)acsii碼的差值
System.out.println(s1.compareTo(s2)); // 不同輸出字符差值-1
System.out.println(s1.compareTo(s3)); // 相同輸出 0
System.out.println(s1.compareTo(s4)); // 前k個字符完全相同,輸出長度差值 -3
}
}
4. 忽略大小寫比較
-
equalsIgnoreCase()
方法:與equals()
方式相同,但是忽略大小寫比較。 -
compareToIgnoreCase()
方法:與compareTo()
方式相同,但是忽略大小寫比較。
public class Main {
public static void main(String[] args) {
String s1 = new String("abc");
String s2 = new String("Abc");
System.out.println(s1.equals(s2)); // false
System.out.println(s1.equalsIgnoreCase(s2)); // true
System.out.println(s1.compareTo(s2));//32
System.out.println(s1.compareToIgnoreCase(s2));// 0
}
}
1.3 字符串查找
字符串查找也是字符串中非常常見的操作,String類提供的常用查找的方法
方法 | 功能 |
---|---|
char charAt(int index) | 返回index位置上字符,如果index為負(fù)數(shù)或者越界,拋出 IndexOutOfBoundsException異常 |
int indexOf(int ch) | 返回ch第一次出現(xiàn)的位置,沒有返回-1 |
int indexOf(int ch, int fromIndex) | 從fromIndex位置開始找ch第一次出現(xiàn)的位置,沒有返回-1 |
int indexOf(String str) | 返回str第一次出現(xiàn)的位置,沒有返回-1 |
int indexOf(String str, int fromIndex) | 從fromIndex位置開始找str第一次出現(xiàn)的位置,沒有返回-1 |
int lastIndexOf(int ch) | 從后往前找,返回ch第一次出現(xiàn)的位置,沒有返回-1 |
int lastIndexOf(int ch, int fromIndex) | 從fromIndex位置開始找,從后往前找ch第一次出現(xiàn)的位置,沒有返 回-1 |
int lastIndexOf(String str) | 從后往前找,返回str第一次出現(xiàn)的位置,沒有返回-1 |
int lastIndexOf(String str, int fromIndex) | 從fromIndex位置開始找,從后往前找str第一次出現(xiàn)的位置,沒有返 回-1 |
public class Main {
public static void main(String[] args) {
String s1 = new String("hello");
// 返回字符串對應(yīng)下標(biāo)的字符
System.out.println(s1.charAt(1)); // e
//返回對應(yīng)字符出來的下標(biāo)位置 從頭開始查找
System.out.println(s1.indexOf('e')); // 1
//返回對應(yīng)字符出來的下標(biāo)位置 從指定位置查找
System.out.println(s1.indexOf('l', 3)); // 3
// 字符串查找 從一個字符串找另一個字符串
System.out.println(s1.indexOf("llo")); // 2
System.out.println(s1.indexOf("ll", 2));// 2
// 返回對應(yīng)字符出來的下標(biāo)位置 從尾開始向前查找
System.out.println(s1.lastIndexOf('l'));// 3
// 返回對應(yīng)字符出來的下標(biāo)位置 從指定位置向前查找
System.out.println(s1.lastIndexOf('l', 1));// -1
System.out.println(s1.lastIndexOf("ll")); // 2
System.out.println(s1.indexOf("ll", 1));// 2
}
}
1.4 轉(zhuǎn)換
1. 數(shù)值和字符串轉(zhuǎn)化
public class Main {
public static void main(String[] args) {
// 數(shù)字轉(zhuǎn)字符串
String s1 = String.valueOf(123);
System.out.println(s1);
String s2 = String.valueOf(12.34);
System.out.println(s2);
String s3 = String.valueOf(true);
System.out.println(s3);
// 字符串轉(zhuǎn)數(shù)字
int num1 = Integer.parseInt("1234");
System.out.println(num1);
double num2 = Double.parseDouble("12.34");
System.out.println(num2);
}
}
2. 大小寫轉(zhuǎn)化
public class Main {
public static void main(String[] args) {
// 小寫轉(zhuǎn)大寫
String s1 = "hello";
System.out.println(s1.toUpperCase());
// 大寫轉(zhuǎn)小寫
String s2 = "HELLO";
System.out.println(s2.toLowerCase());
}
}
問題:轉(zhuǎn)化為大寫/小寫是在原來的字符串上進(jìn)行修改的?
答:不是?。?!,轉(zhuǎn)化為大寫/小寫之后,是產(chǎn)生了一個新的對象
通過String
類源碼中的toUpperCase()
方法和toLowerCase()
方法返回的都是一個新的字符串。
驗證:
3. 字符串轉(zhuǎn)數(shù)組
public class Main {
public static void main(String[] args) {
// 字符串轉(zhuǎn)數(shù)組
String s1 = "hello";
char[] chars = s1.toCharArray();
for (char ch : chars) {
System.out.println(ch);
}
// 數(shù)組為字符串
String s2 = new String(chars);
System.out.println(s2);
}
}
4. 格式化
public class Main {
public static void main(String[] args) {
String s1 = String.format("%d-%d-%d",2021,5,19);
System.out.println(s1);
}
}
1.5 字符串替換
使用一個指定的新的字符串替換掉已有的字符串?dāng)?shù)據(jù),可用的方法如下:
方法 | 說明 |
---|---|
String replaceAll(String regex, String replacement) | 替換所有的指定內(nèi)容 |
String replaceFirst(String regex, String replacement) | 替換收個內(nèi)容 |
public class Main {
public static void main(String[] args) {
String s1 = "abcabcdeabcd";
System.out.println(s1.replace('a', 'p')); // pbcpbcdepbcd
System.out.println(s1.replace("ab","haha")); // hahachahacdehahacd
System.out.println(s1.replaceAll("ab", "uuu")); // uuucuuucdeuuucd
System.out.println(s1.replaceFirst("ab", "ha")); // hacabcdeabcd
}
}
1.6 字符串拆分
可以將一個完整的字符串按照指定的分隔符劃分為若干個子字符串。
方法 | 功能 |
---|---|
String[] split(String regex) | 將字符串全部拆分 |
String[] split(String regex, int limit) | 將字符串以指定的格式,拆分為limit組 |
public class Main {
public static void main(String[] args) {
String s1 = "name = zhangsan&age = 18";
String[] strings = s1.split("&");
for (int i = 0; i < strings.length; i++) {
System.out.println(strings[i]);
}
String s2 = "Hello handsome hello beautiful give me some attention";
// 帥哥美女點點關(guān)注
String[] strings1 = s2.split(" ",12);
// 雖然不能分割12次 但是它能夠保證能分割的最大次數(shù) 不夠就不分了
for (int i = 0; i < strings1.length; i++) {
System.out.println(strings1[i]);
}
}
}
特殊情況:
public class Main {
public static void main(String[] args) {
String s1 = "192.168.1.2";
String[] strings = s1.split("\\.");
for (int i = 0; i < strings.length; i++) {
System.out.println(strings[i]);
}
System.out.println("=========");
String s2 = "C:\\APP\\Java\\jdk1.8\\bin\\java.exe";
String[] strings1 = s2.split("\\\\");
for (int i = 0; i < strings1.length; i++) {
System.out.println(strings1[i]);
}
System.out.println("=========");
String s3 = "name=zhangsan&age=18";
String[] strings2 = s3.split("&|=");
for (int i = 0; i < strings2.length; i++) {
System.out.println(strings2[i]);
}
}
}
【注意事項】:
- 字符"|“,”*“,”+“都得加上轉(zhuǎn)義字符,前面加上”\".
- 而如果是"“,那么就得寫成”\\".
- 如果一個字符串中有多個分隔符,可以用"|"作為連字符.
多次拆分:
public class Main {
public static void main(String[] args) {
String s1 = "name=zhangsan&age=18";
String[] strings = s1.split("&");
for (String x:strings) {
String[] strings2 = x.split("=");
for (String x1 :strings2) {
System.out.println(x1);
}
}
}
}
1.7 字符串的截取
從一個完整的字符串之中截取出部分內(nèi)容。可用方法如下:
方法 | 功能 |
---|---|
String substring(int beginIndex) | 從指定索引截取到結(jié)尾 |
String substring(int beginIndex, int endIndex) | 截取部分內(nèi)容 |
public class Main {
public static void main(String[] args) {
String s1 = "helloworld" ;
System.out.println(s1.substring(5)); // world
System.out.println(s1.substring(0, 5));
// hello 包含 0 下標(biāo)的字符, 不包含 5 下標(biāo)
}
}
1.8 其他操作
方法 | 功能 |
---|---|
String trim() | 去掉字符串中的左右空格,保留中間空格 |
代碼案例:trim()
方法:
public class Main {
public static void main(String[] args) {
String str = " hello world " ;
System.out.println("["+str+"]");// [ hello world ]
System.out.println("["+str.trim()+"]");// [hello world]
}
}
trim
會去掉字符串開頭和結(jié)尾的空白字符(空格, 換行, 制表符等).
2. StringBuilde 類 和 StringBuffer類
由于String的不可更改特性,為了方便字符串的修改,Java中又提供StringBuilder
和StringBuffer
類。這兩個類大 部分功能是相同的,這里介紹 StringBuilder
常用的一些方法,其它需要用到了大家可參閱 [StringBuilder在線文檔](Overview (Java Platform SE 8 ) (oracle.com))
方法 | 功能 |
---|---|
StringBuff append(String str) | 在尾部追加,相當(dāng)于String的+=,可以追加:boolean、char、char[]、 double、float、int、long、Object、String、StringBuff的變量 |
char charAt(int index) | 獲取index位置的字符 |
int length() | 獲取字符串的長度 |
int capacity() | 獲取底層保存字符串空間總的大小 |
void ensureCapacity(int mininmumCapacity) | 擴容 |
void setCharAt(int index, char ch) | 將index位置的字符設(shè)置為ch |
int indexOf(String str) | 返回str第一次出現(xiàn)的位置 |
int indexOf(String str, int fromIndex) | 從fromIndex位置開始查找str第一次出現(xiàn)的位置 |
int lastIndexOf(String str) | 返回最后一次出現(xiàn)str的位置 |
int lastIndexOf(String str, int fromIndex) | 從fromIndex位置開始找str最后一次出現(xiàn)的位置 |
StringBuff insert(int offset, String str) | 在offset位置插入:八種基類類型 & String類型 & Object類型數(shù)據(jù) |
StringBuffer deleteCharAt(int index) | 刪除index位置字符 |
StringBuffer delete(int start, int end) | 刪除[start, end)區(qū)間內(nèi)的字符 |
StringBuffer replace(int start, int end, String str) | 將[start, end)位置的字符替換為str |
String substring(int start) | 從start開始一直到末尾的字符以String的方式返回 |
String substring(int start,int end) | 將[start, end)范圍內(nèi)的字符以String的方式返回 |
StringBuffer reverse() | 反轉(zhuǎn)字符串 |
String toString() | 將所有字符按照String的方式返回 |
public class Main {
public static void main(String[] args) {
StringBuilder sb1 = new StringBuilder("hello");
StringBuilder sb2 = sb1;
// 追加:即尾插-->字符、字符串、整形數(shù)
sb1.append(' '); // hello
sb1.append("world"); // hello world
sb1.append(123); // hello world123
System.out.println(sb1); // hello world123
System.out.println(sb1 == sb2); // true
System.out.println(sb1.charAt(0)); // 獲取0號位上的字符 h
System.out.println(sb1.length()); // 獲取字符串的有效長度14
System.out.println(sb1.capacity()); // 獲取底層數(shù)組的總大小
sb1.setCharAt(0, 'H'); // 設(shè)置任意位置的字符 Hello world123
sb1.insert(0, "Hello world!!!"); // Hello world!!!Hello world123
System.out.println(sb1);
System.out.println(sb1.indexOf("Hello")); // 獲取Hello第一次出現(xiàn)的位置
System.out.println(sb1.lastIndexOf("hello")); // 獲取hello最后一次出現(xiàn)的位置
sb1.deleteCharAt(0); // 刪除首字符
sb1.delete(0,5); // 刪除[0, 5)范圍內(nèi)的字符
String str = sb1.substring(0, 5); // 截取[0, 5)區(qū)間中的字符以String的方式返回
System.out.println(str);
sb1.reverse(); // 字符串逆轉(zhuǎn)
str = sb1.toString(); // 將StringBuffer以String的方式返回
System.out.println(str);
}
}
從上述例子可以看出:String
和StringBuilder
最大的區(qū)別在于**String
的內(nèi)容無法修改**,而StringBuilder
的內(nèi)容可 以修改。頻繁修改字符串的情況考慮使用StringBuilder
。文章來源:http://www.zghlxwxcb.cn/news/detail-798242.html
注意:String
和StringBuilder
類不能直接轉(zhuǎn)換。如果要想互相轉(zhuǎn)換,可以采用如下原則:文章來源地址http://www.zghlxwxcb.cn/news/detail-798242.html
-
String
變?yōu)?code>StringBuilder: 利用StringBuilder
的構(gòu)造方法或append()
方法 -
StringBuilder
變?yōu)?code>String: 調(diào)用toString()
方法。
到了這里,關(guān)于【Java SE語法篇】10.String類的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!