- 一、簡介
-
二、字符串定義
- 2.1 直接定義字符串
- 2.2 通過使用 String 類的構(gòu)造方法來創(chuàng)建字符串
-
三、如何使用Java API幫助文檔
- 3.1 幫助文檔下載地址
- 3.2 幫助文檔使用
- 3.2 中文幫助文檔
-
四、 String字符串和int、double、float 的相互轉(zhuǎn)換
- 4.1 String 轉(zhuǎn)int
- 4.2 String 轉(zhuǎn)Double、Float
- 4.3 int轉(zhuǎn)換為String
- 4.3 Double、Float轉(zhuǎn)換為String
-
五、字符串拼接
- 5.1 使用連接運算符“+”
- 5.2 使用 concat() 方法
- 六 、獲取字符串長度
- 七、字符串大小寫轉(zhuǎn)換
- 八 、去除字符串中的空格
- 九 、截取字符串
- 十、分割字符串
- 十一、字符串替換
-
十二、字符串比較
- 12.1 equals()
- 12.2 equals() 與 == 比較字符
- 12.3 equalsIgnoreCase()
- 12.4 compareTo() 與 compareToIgnoreCase()
-
十三、 字符串查找
- 13.1 charAt()
- 13.2 indexOf()
- 13.3 lastlndexOf()
- 13.4 contains()
-
十四、字符串按指定字符集轉(zhuǎn)byte序列
- 14.1 getBytes()
- 14.2 getBytes(String charsetName)
-
十五、字符復(fù)制
- 15.1 getChars()
- 15.2 copyValueOf()
-
十六、空字符串與null
- 16.1 空字符串與null的區(qū)別
- 16.2 非空判斷
- 16.3 StringUtils的isBlank與isEmpty
-
十七、String、StringBuilder、StringBuffer
- 17.1 比較
- 17.2 繼承結(jié)構(gòu)
- 17.3 使用場景選擇
- 17.4 StringBuffer 常用函數(shù)
一、簡介
Java字符串就是Unicode字符序列。Java里沒有內(nèi)置的字符串類型,而是在標(biāo)準(zhǔn)的類庫中提供了一個預(yù)定義類,String。每個用雙引號""括起來的都是String類的一個實例。
字符串是日常開發(fā)中最常用, Java字符串的一個重要特點就是字符串不可變
二、字符串定義
2.1 直接定義字符串
String str = "www.xiezhrspace.cn";
//或者
String str;
str = "www.xiezhrspace.cn";
2.2 通過使用 String 類的構(gòu)造方法來創(chuàng)建字符串
//① String() 初始化新創(chuàng)建的 String對象,使其表示空字符序列
String str = new String();
//② String(String original) 初始化新創(chuàng)建的String對象,使其表示與參數(shù)相同的字符序列;換句話說,新創(chuàng)建的字符串是參數(shù)字符串的副本。
String str = new String("www.xiezhrspace.cn")
//③ String(char[] value) 分配一個新的字符串,將參數(shù)中的字符數(shù)組元素全部變?yōu)樽址?。該字符?shù)組的內(nèi)容已被復(fù)制,后續(xù)對字符數(shù)組的修改不會影響新創(chuàng)建的字符串
char a[] = {'H','e','l','l','0'};
String sChar = new String(a);
//④ String(char[] value, int offset, int count) 分配一個新的 String,它包含來自該字符數(shù)組參數(shù)一個子數(shù)組的字符。offset 參數(shù)是子數(shù)組第一個字符的索引,count 參數(shù)指定子數(shù)組的長度。該子數(shù)組的內(nèi)容已被賦值,后續(xù)對字符數(shù)組的修改不會影響新創(chuàng)建的字符串
char a[]={'H','e','l','l','o'};
String sChar=new String(a,1,4);
...
String
提供的構(gòu)造方法很多,文章只列舉常用的,其余的可自行查找Java幫助文檔。幫助文檔的使用參照下一小節(jié)
三、如何使用Java API幫助文檔
3.1 幫助文檔下載地址
https://www.oracle.com/java/technologies/downloads/
下載完解壓后目錄如下
3.2 幫助文檔使用
① 雙擊index.html打開
② 搜索框中輸入關(guān)鍵字String
找到j(luò)ava.lang包下的String
③ 查看String
類的幫助信息String
類的基本信息String
類public/protected 修飾的屬性String
類public/protected 修飾所有構(gòu)造器String
類public/protected 修飾所有構(gòu)造器
3.2 中文幫助文檔
如果小伙伴看英文比較吃力,這里也提供了中文幫助文檔下載地址(文檔包含jdk1.6~jdk10 的幫助文檔)。
注: 中文幫助文檔采用的是工具翻譯的,有些地方可能不準(zhǔn)確,請結(jié)合著官方英文文檔查看
鏈接:https://pan.baidu.com/s/1Rh-o1i-LCjEPNB4EyO9FrQ
提取碼:7kms
四、 String字符串和int、double、float 的相互轉(zhuǎn)換
4.1 String 轉(zhuǎn)int
String 轉(zhuǎn)換 int 時,String 的值一定是整數(shù),否則會報數(shù)字轉(zhuǎn)換異常(java.lang.NumberFormatException)
Integer.parseInt(String s)
Integer.valueOf(String s)
public class StringTest {
public static void main(String[] args) {
System.out.println(Integer.parseInt("123"));
System.out.println(Integer.valueOf("345"));
}
}
//輸出結(jié)果為
123
345
4.2 String 轉(zhuǎn)Double、Float
String 轉(zhuǎn)換 Double、Float 時,String 的值一定是浮點類型,否則會報數(shù)字轉(zhuǎn)換異常(java.lang.NumberFormatException)
Double.parseDouble(String s)
Double.valueOf(String s)
Float.parseFloat(String s)
Float.valueOf(String s)
public class StringTest {
public static void main(String[] args) {
System.out.println(Double.parseDouble("12.45"));
System.out.println(Double.valueOf("12.45"));
System.out.println(Float.parseFloat("25.68"));
System.out.println(Float.valueOf("25.68"));
}
}
//輸出結(jié)果為
12.45
12.45
25.68
25.68
4.3 int轉(zhuǎn)換為String
使用第三種方法相對第一第二種耗時比較大。在使用第一種 valueOf() 方法時,注意 valueOf 括號中的值不能為空,否則會報空指針異常(NullPointerException)
String.valueOf( Integer i)
Integer.toString( Integer i)
"" + Integer i
public class StringTest {
public static void main(String[] args) {
System.out.println(String.valueOf(123));
System.out.println(Integer.toString(345));
System.out.println(456 + "");
}
}
//輸出結(jié)果為
123
345
456
4.3 Double、Float轉(zhuǎn)換為String
使用第三種方法相對第一第二種耗時比較大。在使用第一種 valueOf() 方法時,注意 valueOf 括號中的值不能為空,否則會報空指針異常(NullPointerException)
String.valueOf(Double d)
Double.toString(Double d)
"" + Double d
String.valueOf(Float d)
Float.toString(Float d)
"" + Float f
public class StringTest {
public static void main(String[] args) {
public class StringTest {
public static void main(String[] args) {
System.out.println(String.valueOf(20.48d));
System.out.println(Double.toString(20.48d));
System.out.println(20.48d + "");
System.out.println(String.valueOf(10.24f));
System.out.println(Float.toString(10.24f));
System.out.println(10.24f + "");
}
}
}
}
//輸出結(jié)果為
20.48
20.48
20.48
10.24
10.24
10.24
五、字符串拼接
5.1 使用連接運算符“+”
str1+str2
public class StringTest {
public static void main(String[] args) {
System.out.println("微信公眾號:" + "XiezhrSpace");
}
}
//輸出
微信公眾號:XiezhrSpace
5.2 使用 concat() 方法
str1.concat(str2)
public class StringTest {
public static void main(String[] args) {
System.out.println("個人博客:".concat("www.xiezhrspace.cn"));
}
}
// 輸出
個人博客:www.xiezhrspace.cn
六 、獲取字符串長度
str.length()
public class StringTest {
public static void main(String[] args) {
String str1 = "公眾號:XiezhrSpace";
String str2 = "個人博客:www.xiezhrspace.cn";
System.out.println("str1長度:"+str1.length());
System.out.println("str2長度:"+str2.length());
}
}
//輸出
str1長度:15
str2長度:23
七、字符串大小寫轉(zhuǎn)換
-
str.toLowerCase()
將字符串中的字母全部轉(zhuǎn)換為小寫,非字母不受影響 -
str.toUpperCase()
將字符串中的字母全部轉(zhuǎn)換為大寫,非字母不受影響
public class StringTest {
public static void main(String[] args) {
String str ="Hello World!";
System.out.println("原始字符串:"+str);
System.out.println("使用toLowerCase() 方法之后為:" + str.toLowerCase());
System.out.println("使用toUpperCase() 方法之后為:" + str.toUpperCase());
}
}
//輸出
原始字符串:Hello World!
使用toLowerCase() 方法之后為:hello world!
使用toUpperCase() 方法之后為:HELLO WORLD!
八 、去除字符串中的空格
字符串中存在的首尾空格一般情況下都沒有任何意義,如字符串“ Hello ”,但是這些空格會影響到字符串的操作,如連接字符串或比較字符串等,所以應(yīng)該去掉字符串中的首尾空格,這需要使用 String 類提供的 trim() 方法
str.trim()
str.replace((char) 12288, ' '); str.trim()
注意:
-
trim()
只能去掉字符串中前后的半角空格(英文空格),而無法去掉全角空格(中文空格)。
這時候我們只能先將全角空格替換為半角空格再進(jìn)行操作,其中替換是 String 類的replace()
方法 - 12288 是中文全角空格的 unicode 編碼
//字符串中的每個空格占一個位置,直接影響了計算字符串的長度
public class StringTest {
public static void main(String[] args) {
String str = " hello ";
System.out.println(str.length()); // 輸出 7
System.out.println(str.trim().length()); // 輸出 5
}
}
//輸出
7
5
//去除全角空格實例
public class StringTest {
public static void main(String[] args) {
String str = " hello";
//帶有全角的空格沒有去掉
System.out.println(str.trim().length());
//去除全角空格
System.out.println(str.replace((char) 12288, ' ').trim().length());
}
}
//輸出
6
5
九 、截取字符串
-
substring(int beginIndex)
//指定位置截取到字符串結(jié)尾 -
substring(int beginIndex,int endIndex)
是截取指定范圍的內(nèi)容
substring() 方法是按字符截取,而不是按字節(jié)截取
①substring(int beginIndex)
//調(diào)用時,括號中是需要提取字符串的開始位置,方法的返回值是提取的字符串
public class StringTest {
public static void main(String[] args) {
String str = "關(guān)注XiezhrSpace公眾號";
System.out.println(str.substring(2));
}
}
//輸出
XiezhrSpace公眾號
②substring(int beginIndex,int endIndex)
//方法中的 beginIndex 表示截取的起始索引,截取的字符串中包括起始索引對應(yīng)的字符;
//endIndex 表示結(jié)束索引,截取的字符串中不包括結(jié)束索引對應(yīng)的字符
public class StringTest {
public static void main(String[] args) {
String str = "關(guān)注XiezhrSpace公眾號";
System.out.println(str.substring(2,13));
}
}
//輸出
XiezhrSpace
注意:, 對于開始位置 beginIndex, Java 是基于字符串的首字符索引為 0 處理的,但是對于結(jié)束位置 endIndex,Java 是基于字符串的首字符索引為 1 來處理的 。具體如下圖所示
十、分割字符串
-
str.split(String sign)
-
str.split(String sign,int limit)
-
str 為需要分割的目標(biāo)字符串。
-
sign 為指定的分割符,可以是任意字符串。
-
limit 表示分割后生成的字符串的限制個數(shù),如果不指定,則表示不限制,直到將整個目標(biāo)字符串完全分割為止。
public class StringTest {
public static void main(String[] args) {
String str = "蘋果,香蕉,獼猴桃,梨";
String arr1[] = str.split(",");
String arr2[] = str.split(",",3);
System.out.println("①分割所有水果");
for (int i = 0; i < arr1.length; i++) {
System.out.println(arr1[i]);
}
System.out.println("②分割取前兩個水果,其余不分割");
for (int i = 0; i < arr2.length; i++) {
System.out.println(arr2[i]);
}
}
}
//輸出
①分割所有水果
蘋果
香蕉
獼猴桃
梨
②分割取前兩個水果,其余不分割
蘋果
香蕉
獼猴桃,梨
對于 .
,|
,$
,&
,*
, .
,^
等轉(zhuǎn)義字符,程序中使用時,需要加上\\
。 實例如下
public class StringTest {
public static void main(String[] args) {
String str1 = "蘋果|香蕉|獼猴桃|梨";
String str2 = "黃色$橙色$紅色$白色";
String arr1[] = str1.split("\\|");
String arr2[] = str2.split("\\$");
System.out.println("分割以|分割的水果:");
for (int i = 0; i < arr1.length; i++) {
System.out.println(arr1[i]);
}
System.out.println("分割以$為分隔符的顏色:");
for (int i = 0; i < arr2.length; i++) {
System.out.println(arr2[i]);
}
}
}
//輸出結(jié)果
分割以|分割的水果:
蘋果
香蕉
獼猴桃
梨
分割以$為分隔符的顏色:
黃色
橙色
紅色
白色
//多層分隔符解析
public class StringTest {
public static void main(String[] args) {
String str = "xiezhr相關(guān)信息^個人公賬號|XiezhrSpace$個人博客|www.xiezhrspace.cn";
String arr1[] = str.split("\\^");
String arr2[] = arr1[1].split("\\$");
String arr3[] ={};
System.out.println(arr1[0]);
for (int i = 0; i < arr2.length; i++) {
arr3= arr2[i].split("\\|");
for (int i1 = 0; i1 < arr3.length; i1++) {
System.out.println(arr3[i1]);
}
}
}
}
//輸出
xiezhr相關(guān)信息
個人公賬號
XiezhrSpace
個人博客
www.xiezhrspace.cn
十一、字符串替換
str.replace(char oldChar, char newChar)
將目標(biāo)字符串中的指定字符(串)替換成新的字符(串)
- oldChar 表示被替換的字符串
- newChar 表示用于替換的字符串
str.replaceFirst(String regex, String replacement)
將目標(biāo)字符串中匹配某正則表達(dá)式的第一個子字符串替換成新的字符串
- regex 表示正則表達(dá)式
- replacement 表示用于替換的字符串
str.replaceAll(String regex, String replacement)
將目標(biāo)字符串中匹配某正則表達(dá)式的所有子字符串替換成新的字符串
- regex 表示正則表達(dá)式
- replacement 表示用于替換的字符串
public class StringTest {
public static void main(String[] args) {
String str1 ="個人公眾號:XiezhrSpace";
String str2 ="xiezhr love programming";
System.out.println("原始字符串:" + str1);
System.out.println("替換后:"+str1.replace(":", "|"));
System.out.println("原始字符串:" + str2);
System.out.println("替換后:"+str2.replace("programming", "anime"));
}
}
//輸出
原始字符串:個人公眾號:XiezhrSpace
替換后:個人公眾號|XiezhrSpace
原始字符串:xiezhr love programming
替換后:xiezhr love anime
public class StringTest {
public static void main(String[] args) {
String str ="中國移動:https://www.10086.cn/ 10086:https://www.10086.cn/";
System.out.println("匹配成功:");
System.out.println(str.replaceFirst("10086", "xiezhrspace"));
System.out.println("未匹配成功:");
System.out.println(str.replaceFirst("mobile", "xiezhrspace"));
}
}
//輸出
匹配成功:
中國移動:https://www.xiezhrspace.cn/ 10086:https://www.10086.cn/
未匹配成功:
中國移動:https://www.10086.cn/ 10086:https://www.10086.cn/
public class StringTest {
public static void main(String[] args) {
String str ="中國移動:https://www.10086.cn/ 10086:https://www.10086.cn/";
System.out.println("匹配成功:");
System.out.println(str.replaceAll("10086", "xiezhrspace"));
System.out.println("未匹配成功:");
System.out.println(str.replaceAll("mobile", "xiezhrspace"));
}
}
//輸出
匹配成功:
中國移動:https://www.xiezhrspace.cn/ xiezhrspace:https://www.xiezhrspace.cn/
未匹配成功:
中國移動:https://www.10086.cn/ 10086:https://www.10086.cn/
十二、字符串比較
str1.equals(str2)
str1.equalsIgnoreCase(str2)
str1.compareTo(str2);
12.1 equals()
逐個地比較兩個字符串的每個字符是否相同。如果兩個字符串具有相同的字符和長度,它返回 true,否則返回 false。字符大小寫不同,返回false
public class StringTest {
public static void main(String[] args) {
String str1 ="xiezhr";
String str2 = new String("xiezhr");
String str3 = "XIEZHR";
System.out.println("str1與str2比較結(jié)果:" + str1.equals(str2));
System.out.println("str1與str3比較結(jié)果:" + str1.equals(str3));
}
}
//輸出結(jié)果
str1與str2比較結(jié)果:true
str1與str3比較結(jié)果:false
12.2 equals() 與 == 比較字符
== 比較引用地址是否相同,equals() 比較字符串的內(nèi)容是否相同
public class StringTest {
public static void main(String[] args) {
String str1 ="xiezhr";
String str2 = new String("xiezhr");
System.out.println("使用equals方法比較的結(jié)果:");
System.out.println(str1.equals(str2));
System.out.println("使用==比較的結(jié)果:");
System.out.println(str1 == str2);
}
}
//輸出
使用equals方法比較的結(jié)果:
true
使用==比較的結(jié)果:
false
12.3 equalsIgnoreCase()
字符串與指定的對象比較,不考慮大小寫
public class StringTest {
public static void main(String[] args) {
String str1 ="xiezhr";
String str2 ="XIEZHR";
String str3 = new String("xiezhr");
System.out.println("str1與str2通過equalsIgnoreCase比較結(jié)果:" + str1.equalsIgnoreCase(str2));
System.out.println("str1與str3通過equalsIgnoreCase比較結(jié)果:" + str1.equalsIgnoreCase(str3));
}
}
//輸出
str1與str2通過equalsIgnoreCase比較結(jié)果:true
str1與str3通過equalsIgnoreCase比較結(jié)果:true
12.4 compareTo() 與 compareToIgnoreCase()
基于字符串各個字符的 Unicode 值,按字典順序(ASCII碼順序)比較兩個字符串的大小
如果第一個字符和參數(shù)的第一個字符不等,結(jié)束比較,返回他們之間的長度差值(ASCII碼差值)
如果第一個字符和參數(shù)的第一個字符相等,則以第二個字符和參數(shù)的第二個字符做比較,以此類推,直至不等為止,返回該字符的ASCII碼差值
如果兩個字符串不一樣長,可對應(yīng)字符又完全一樣,則返回兩個字符串的長度差值
compareToIgnoreCase方法可以忽略大小寫
- 如果參數(shù)字符串等于此字符串,則返回值 0;
- 如果此字符串小于字符串參數(shù),則返回一個小于 0 的值;
- 如果此字符串大于字符串參數(shù),則返回一個大于 0 的值。
public class StringTest {
public static void main(String[] args) {
String str1 ="xiezhr";
String str2 ="XIEZHR";
String str3 = new String("xiezhr");
String str4 = "xiezhr";
String str5 ="xiezhrspace";
System.out.println(str1.compareTo(str2));
System.out.println(str1.compareTo(str3));
System.out.println(str1.compareTo(str4));
System.out.println(str1.compareTo(str5));
System.out.println(str1.compareToIgnoreCase(str2));
}
}
//輸出
32
0
0
-5
0
十三、 字符串查找
13.1 charAt()
字符串本質(zhì)上是由一個個字符組成的字符數(shù)組,因此它也有索引,索引跟數(shù)組一樣從零開始。charAt() 方法可以在字符串內(nèi)根據(jù)指定的索引查找字符
public class StringTest {
public static void main(String[] args) {
String str ="www.xiezhrspace.cn";
System.out.println(str.charAt(0));
System.out.println(str.charAt(4));
System.out.println(str.charAt(5));
System.out.println(str.charAt(12));
}
}
//輸出
w
x
i
a
13.2 indexOf()
①public int indexOf(int ch): 返回指定字符在字符串中第一次出現(xiàn)處的索引,如果此字符串中沒有這樣的字符,則返回 -1
②public int indexOf(int ch, int fromIndex): 返回從 fromIndex 位置開始查找指定字符在字符串中第一次出現(xiàn)處的索引,如果此字符串中沒有這樣的字符,則返回 -1
③int indexOf(String str): 返回指定字符在字符串中第一次出現(xiàn)處的索引,如果此字符串中沒有這樣的字符,則返回 -1
④int indexOf(String str, int fromIndex): 返回從 fromIndex 位置開始查找指定字符在字符串中第一次出現(xiàn)處的索引,如果此字符串中沒有這樣的字符,則返回 -1
- ch -- 字符,Unicode 編碼。
- fromIndex -- 開始搜索的索引位置,第一個字符是 0 ,第二個是 1 ,以此類推。
- str -- 要搜索的子字符串
public class StringTest {
public static void main(String[] args) {
String str ="XiezhrSpace";
System.out.println(str.indexOf("e"));
System.out.println(str.indexOf("pa"));
System.out.println(str.indexOf("e", 4));
}
}
//輸出
2
7
10
13.3 lastlndexOf()
用于返回字符(串)在指定字符串中最后一次出現(xiàn)的索引位置,如果能找到則返回索引值,否則返回 -1
lastlndexOf 方法的四種形式
-
public int lastIndexOf(int ch)
: 返回指定字符在目標(biāo)字符串中最后一次出現(xiàn)處的索引,如果指定字符串中沒有指定的字符,返回 -1。 -
public int lastIndexOf(int ch, int fromIndex)
: 返回指定字符在目標(biāo)字符串中最后一次出現(xiàn)處的索引,從指定的索引處開始進(jìn)行反向搜索,如果目標(biāo)字符串中沒有指定字符,返回 -1。 -
public int lastIndexOf(String str)
: 返回指定子字符串在目標(biāo)字符串中最后一次出現(xiàn)處的索引,如果目標(biāo)字符串中沒有指定字符,返回 -1。 -
public int lastIndexOf(String str, int fromIndex)
: 返回指定子字符串在目標(biāo)符串中最后一次出現(xiàn)處的索引,從指定的索引開始反向搜索,如果目標(biāo)字符串中沒有指定的字符,返回 -1。
public class StringTest {
public static void main(String[] args) {
String str = new String("個人博客:www.xiezhrspace.cn");
String str1 = "xiezhr";
String str2 = "cn";
System.out.print("查找指定字符 w 在目標(biāo)字符str中最后出現(xiàn)的位置 :" );
System.out.println(str.lastIndexOf( 'w' ));
System.out.print("從第2個位置查找指定字符 w在目標(biāo)字符串str最后出現(xiàn)的位置 :" );
System.out.println(str.lastIndexOf( 'w', 14 ));
System.out.print("指定子字符串 str1 在目標(biāo)字符串str最后出現(xiàn)的位置:" );
System.out.println( str.lastIndexOf( str1 ));
System.out.print("從第7個位置開始查找指定字符串 str1在目標(biāo)字符串中最后出現(xiàn)的位置 :" );
System.out.println( str.lastIndexOf( str1, 7 ));
System.out.print("指定字符串 str2 在目標(biāo)字符串str最后出現(xiàn)的位置 :" );
System.out.println(str.lastIndexOf( str2 ));
}
}
//輸出
查找指定字符 w 在目標(biāo)字符str中最后出現(xiàn)的位置 :7
從第2個位置查找指定字符 w在目標(biāo)字符串str最后出現(xiàn)的位置 :7
指定子字符串 str1 在目標(biāo)字符串str最后出現(xiàn)的位置:9
從第7個位置開始查找指定字符串 str1在目標(biāo)字符串中最后出現(xiàn)的位置 :-1
指定字符串 str2 在目標(biāo)字符串str最后出現(xiàn)的位置 :21
13.4 contains()
查找字符串中是否包含目標(biāo)字符(串)
public class StringTest {
public static void main(String[] args) {
String str = "xiezhrspace";
System.out.println(str.contains("xiezhr"));
System.out.println(str.contains("cn"));
}
}
//輸出
true
false
十四、字符串按指定字符集轉(zhuǎn)byte序列
14.1 getBytes()
按指定的字符集將字符串編碼為 byte 序列,并將結(jié)果存儲到一個新的 byte 數(shù)組中
14.2 getBytes(String charsetName)
默認(rèn)字符集將字符串編碼為 byte 序列,并將結(jié)果存儲到一個新的 byte 數(shù)組中
import java.io.UnsupportedEncodingException;
public class StringTest {
public static void main(String[] args) {
String str = "網(wǎng)名xiezhr";
byte[] bytes1 = null;
byte[] bytes2 = null;
byte[] gbks = null;
byte[] bytes = str.getBytes();
try {
bytes1 = str.getBytes("utf-8");
bytes2 = str.getBytes("ISO-8859-1");
gbks = str.getBytes("GBK");
}catch (UnsupportedEncodingException e){
System.out.println("不支持的字符集"+e.getMessage());
}
System.out.println("按默認(rèn)字符集將字符串轉(zhuǎn)byte數(shù)組:");
for (byte aByte : bytes) {
System.out.print(aByte+" ");
}
System.out.println();
System.out.println("按utf-8編碼將字符串轉(zhuǎn)bytes數(shù)組:");
for (byte b1 : bytes1) {
System.out.print(b1+" ");
}
System.out.println();
System.out.println("按ISO-8859-1編碼將字符串轉(zhuǎn)bytes數(shù)組:");
for (byte b2 : bytes2) {
System.out.print(b2+" ");
}
System.out.println();
System.out.println("按GBK編碼將字符串轉(zhuǎn)bytes數(shù)組:");
for (byte gbk : gbks) {
System.out.print(gbk+" ");
}
}
}
//輸出
按默認(rèn)字符集將字符串轉(zhuǎn)byte數(shù)組:
-25 -67 -111 -27 -112 -115 120 105 101 122 104 114
按utf-8編碼將字符串轉(zhuǎn)bytes數(shù)組:
-25 -67 -111 -27 -112 -115 120 105 101 122 104 114
按ISO-8859-1編碼將字符串轉(zhuǎn)bytes數(shù)組:
63 63 120 105 101 122 104 114
按GBK編碼將字符串轉(zhuǎn)bytes數(shù)組:
-51 -8 -61 -5 120 105 101 122 104 114
十五、字符復(fù)制
15.1 getChars()
將字符從字符串復(fù)制到目標(biāo)字符數(shù)組
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
- srcBegin -- 字符串中要復(fù)制的第一個字符的索引。
- srcEnd -- 字符串中要復(fù)制的最后一個字符之后的索引。
- dst -- 目標(biāo)數(shù)組。
- dstBegin -- 目標(biāo)數(shù)組中的起始偏移量
public class StringTest {
public static void main(String[] args) {
String Str1 = new String("www.xiezhrspace.cn");
char[] Str2 = new char[15];
try {
Str1.getChars(4, 15, Str2, 3);
System.out.print("復(fù)制的字符串為:" );
System.out.println(Str2 );
} catch( Exception e) {
System.out.println(e.getMessage());
}
}
}
//輸出,新字符串Str2 是從第三位復(fù)制的
復(fù)制的字符串為: xiezhrspace
15.2 copyValueOf()
將字符數(shù)組中指定字符復(fù)制到目標(biāo)字符
① public static String copyValueOf(char[] data)
- data -- 字符數(shù)組
② public static String copyValueOf(char[] data, int offset, int count)
- data -- 字符數(shù)組
- offset -- 子數(shù)組的初始偏移量
- count -- 子數(shù)組的長度
public class StringTest {
public static void main(String[] args) {
char[] str1 ={'w','w','w',':','x','i','e','z','h','r','s','p','a','c', 'e','.','c','n' };
String str2 = null;
String str3 = null;
System.out.println(str2.copyValueOf(str1));
System.out.println(str3.copyValueOf(str1, 4, 11));
}
}
//輸出
www:xiezhrspace.cn
xiezhrspace
十六、空字符串與null
一個比較容易混淆的知識點。空串是長度為0的字符串,null表示沒有引用任何對象
16.1 空字符串與null的區(qū)別
- String str = null ;
表示聲明一個字符串對象的引用,但指向為null,也就是說還沒有指向任何的內(nèi)存空間; - String str = "";
表示聲明一個字符串類型的引用,其值為""空字符串,這個str引用指向的是空字符串的內(nèi)存空間; - String str = new String();
創(chuàng)建一個字符串對象的默認(rèn)值為""
/**
字符串對象與null的值不相等,且內(nèi)存地址也不相等;
空字符串對象與null的值不相等,且內(nèi)存地址也不相等;
new String()創(chuàng)建一個字符串對象的默認(rèn)值為""
**/
public class StringTest {
public static void main(String[] args) {
String str1 = new String();
String str2 = null;
String str3 = "";
System.out.println(str1==str2);
System.out.println(str1.equals(str2));
System.out.println(str2==str3);
System.out.println(str3.equals(str2));
System.out.println(str1==str3);
System.out.println(str1.equals(str3));
}
}
//輸出
false //內(nèi)存地址的比較,返回false
false //值的比較,返回false
false //內(nèi)存地址的比較,返回false
false //值的比較,返回false
false //內(nèi)存地址的比較,返回false
true //值的比較,返回true
16.2 非空判斷
執(zhí)行下面代碼,會拋出java.lang.NullPointerException 。這也是我們?nèi)粘i_發(fā)中經(jīng)常見到的報錯。
所以,字符串非空判斷顯得尤為重要
public class StringTest {
public static void main(String[] args) {
String str = null;
str.length();
}
}
// 報空指針異常
Exception in thread "main" java.lang.NullPointerException
at StringTest.main(StringTest.java:5)
非空判斷一般包含空字符串和null判斷,常見的判斷方法主要有以下幾種
① 最多人使用的一個方法, 直觀, 方便, 但效率很低
注: s==null 判斷需要寫在前面,要不然還是會報NullPointerException
if(!(s == null || s.equals(""))){
System.out.println("業(yè)務(wù)邏輯代碼");
};
//或者
if(str !=null &&!"".equals(str)){
System.out.println("業(yè)務(wù)邏輯代碼");
}
②比較字符串長度, 效率比第一種方法高
if(!(str==null||str.length()==0)){
System.out.println("業(yè)務(wù)邏輯代碼");
}
if(str!=null&&str.length()!=0){
System.out.println("業(yè)務(wù)邏輯代碼");
}
}
③ Java SE 6.0 才開始提供的方法, 效率和方法②差不多, 但出于兼容性考慮, 推薦使用方法二
if(!(str==null||str.isEmpty())){
System.out.println("業(yè)務(wù)邏輯代碼");
}
if(str!=null&& !str.isEmpty()){
System.out.println("業(yè)務(wù)邏輯代碼");
}
16.3 StringUtils的isBlank與isEmpty
與java.lang這個包作用類似,Commons Lang 包是由apache 提供的jar包。這一組API也是提供一些基礎(chǔ)的、通用的操作和處理
官方下載地址:https://commons.apache.org/proper/commons-lang/download_lang.cgi
maven 包引用
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
commons-lang3 提供了很多常用的基礎(chǔ)操作處理,包括字符串、日期、數(shù)組等等。
由于本文主要是說字符串String,所以我們只對其中的StringUtils的isBlank與isEmpty 方法說明。
判斷字符串為空,一般會遇到 null 、"" 、字符串中間有空格 " ", 下面是兩個方法處理結(jié)果
① public static boolean isBlank(String str)
import org.apache.commons.lang3.StringUtils;
public class StringTest {
public static void main(String[] args) {
System.out.println(StringUtils.isBlank(null));
System.out.println(StringUtils.isBlank(""));
System.out.println(StringUtils.isBlank(" "));
System.out.println(StringUtils.isBlank(" "));
System.out.println(StringUtils.isBlank("\t \n \f \r"));
System.out.println(StringUtils.isBlank("\\"));
System.out.println(StringUtils.isBlank("公眾號XiezhrSpace"));
System.out.println(StringUtils.isBlank(" 公眾號XiezhrSpace "));
}
}
//輸出
true
true
true
true
true
false
false
false
② public static boolean isEmpty(String str)
import org.apache.commons.lang3.StringUtils;
public class StringTest {
public static void main(String[] args) {
System.out.println(StringUtils.isEmpty(null));
System.out.println(StringUtils.isEmpty(""));
System.out.println(StringUtils.isEmpty(" ")); //StringUtils 中空格作非空處理
System.out.println(StringUtils.isEmpty(" "));
System.out.println(StringUtils.isEmpty("\t \n \f \r"));
System.out.println(StringUtils.isEmpty("\\"));
System.out.println(StringUtils.isEmpty("公眾號XiezhrSpace"));
System.out.println(StringUtils.isEmpty(" 公眾號XiezhrSpace "));
}
}
//輸出
true
true
false
false
false
false
false
false
當(dāng)然了,StringUtils工具類還有對應(yīng)的isNotBlank和isNotEmpty 方法,意思是不為空。
十七、String、StringBuilder、StringBuffer
具體區(qū)別可以參考https://blog.csdn.net/itchuxuezhe_yang/article/details/89966303 這篇博文,寫的還是挺好的。
17.1 比較
-
String
類是不可變類,即一旦一個 String 對象被創(chuàng)建以后,包含在這個對象中的字符序列是不可改變的; -
StringBuffer
和StringBuilder
支持可變字符串; -
StringBuilder
和StringBuffer
功能基本相似,方法也差不多; -
StringBuffer
是線程安全的,而StringBuilder
則沒有實現(xiàn)線程安全功能; -
StringBuilder
由于沒有實現(xiàn)線程安全,所以效率要比StringBuffer
高;
17.2 繼承結(jié)構(gòu)
17.3 使用場景選擇
- 操作少量的數(shù)據(jù)使用 String。
- 單線程操作大量數(shù)據(jù)使用 StringBuilder(大多數(shù)情況推薦使用)。
- 多線程操作大量數(shù)據(jù)使用 StringBuffer。
public class StringTest {
public static void main(String[] args) {
StringBuilder sbd = new StringBuilder();
StringBuffer sbf = new StringBuffer();
String str1 ="xiezhr個人信息:";
String str2 ="博客:www.xiezhrspace.cn";
String str3 ="公眾號:XiezhrSpace";
String str =str1+str2+str3;
sbd.append(str1);
sbd.append(str2);
sbd.append(str3);
sbf.append(str1);
sbf.append(str2);
sbf.append(str3);
System.out.println("String拼接字符串:");
System.out.println(str);
System.out.println("StringBuilder拼接字符串:");
System.out.println(sbd.toString());
System.out.println("StringBuffer拼接字符串:");
System.out.println(sbf.toString());
}
}
//輸出
String拼接字符串:
xiezhr個人信息:博客:www.xiezhrspace.cn公眾號:XiezhrSpace
StringBuilder拼接字符串:
xiezhr個人信息:博客:www.xiezhrspace.cn公眾號:XiezhrSpace
StringBuffer拼接字符串:
xiezhr個人信息:博客:www.xiezhrspace.cn公眾號:XiezhrSpace
17.4 StringBuffer 常用函數(shù)
append(String s)
//追加一個字符串reverse()
//將字符串反轉(zhuǎn)delete(int start, int end)
//刪除指定位置字符串insert(int offset, String str)
//在指定位置插入字符串replace(int start, int end, String str)
//將指定位置字符串替換為新字符串
public class StringTest {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
sb.append("XiezhrSpace!!!");
System.out.println(sb);
sb.append("m");
System.out.println(sb);
sb.insert(0,"公眾號:");
System.out.println(sb);
sb.delete(16,19);
System.out.println(sb);
sb.replace(15,16,"**");
System.out.println(sb);
sb.reverse();
System.out.println(sb);
}
}
//輸出
XiezhrSpace!!!
XiezhrSpace!!!m
公眾號:XiezhrSpace!!!m
公眾號:XiezhrSpace!
公眾號:XiezhrSpace**
**ecapSrhzeiX:號眾公
文章來源:http://www.zghlxwxcb.cn/news/detail-448789.html
本期到此結(jié)束,我們下期再見~(●'?'●)文章來源地址http://www.zghlxwxcb.cn/news/detail-448789.html
到了這里,關(guān)于Java中的字符串的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!