String類是一個字符串類型的類,使用“xxxx”定義的內(nèi)容都是字符串,雖然這個類在使用上有一些特殊,但是String本身是一個類。
一.String的實例化兩種方式
1.直接賦值實例化
String Name = "xxxx";
以上是String對象的直接賦值,以上的代碼并沒有使用關(guān)鍵字new進行。String類也是類,所以也有構(gòu)造方法
2.使用構(gòu)造方法實例化
public String(String str);
可以通過構(gòu)造方法為String類對象實例話,但在構(gòu)造里面依然要接收一個本類對象
二.字符串的比較
先看一個例子
String str1 = "abc";
String str2 = "abc";
System.out.println(str1 == str2);
System.out.println(str1.equals(str2));
運行結(jié)果為
true
true
== 比較兩個對象是否相同:地址
equals 比較內(nèi)容是否相同
可以看出,內(nèi)容相同的字符串,可以享用的同一片內(nèi)存空間
再來看第二個例子:
String str1 = "abc";
String str2 = "abc";
String str3 = new String("abc");
System.out.println(str1 == str3);
System.out.println(str1.equals(str3));
運行結(jié)果 第一個為false第二個為true
當我們使用new來構(gòu)造字符串對象的時候,不管字符串常量池中有沒有相同內(nèi)容的對象的引用,新的字符串對象都會創(chuàng)建。
我們再用內(nèi)存關(guān)系圖來分析



字符串的應用
1.使用字節(jié)數(shù)組 創(chuàng)建一個字符串
byte[] name = {'A','b','c'};
String str4 = new String(name);
System.out.println(str4);
byte[] name2 = {97,98,99};
String str5 = new String(name2);
System.out.println(str5);
運行結(jié)果
Abc
abc
2.使用字節(jié)數(shù)組的一部分 創(chuàng)建一個字符串
String str6 = new String(name,0,2);//從byte[0]開始,共有兩個字節(jié)
System.out.println(str6);
運行結(jié)果
Ab
3.獲取字符串中的一個字符
charAt
char[] hello = {'你','好','啊'};
String h = new String(hello);
System.out.println(h);
char c = h.charAt(0);
System.out.println(c);
運行結(jié)果為
你好啊
你
4.兩個字符串的比較 compareTo
可以知道大小關(guān)系 0 : 相同 >0:大于 <0:小于
int result = str4.compareTo(str1);
System.out.println(result);
運行結(jié)果
-32
5.兩個字符串的連接
concat
String nStr = str5.concat(h);
System.out.println(nStr);
運行結(jié)果
abc你好啊
6.判斷一個字符是否包含另外一個字符串
contains
boolean r = "hello".contains("lle");
System.out.println(r);
運行結(jié)果
flase
7.判斷是否以某個字符串結(jié)尾
String url = "http://www.baidu.com";
if (url.endsWith(".com")){
System.out.println("網(wǎng)址");
}
if (url.startsWith("www",7)){
System.out.println("萬維網(wǎng)");
}
運行結(jié)果
網(wǎng)址
萬維網(wǎng)
8.兩個字符串進行比較
equals
if ("abc".equals("ABC")){
System.out.println("相同");
}else {
System.out.println("不相同");
}
運行結(jié)果
不相同
9.判斷一個子類字符串在另外一個字符串里面的位置
indexOf 不存在返回值為-1
String i1 = "hello java";
int index = i1.indexOf("javeee");
System.out.println(index);
運行結(jié)果
-1
10.獲取字符串的長度
length
-
獲取字符串
substring 從index到結(jié)尾String sStr = i1.substring(6); System.out.println(sStr);
運行結(jié)果
java
從0開始 到5
String sStr2 = i1.substring(0,5);
System.out.println(sStr2);
運行結(jié)果
hello
12.將字符串轉(zhuǎn)化為字符數(shù)組
toCharArray
13.將所有字符化為小寫
toLowerCase/toUpperCase
14.將字符串前面和后面的空格字符刪除
trim()
15.可變字符串
StringBuffer 線程安全 效率不高
StringBuilder 線程不安全 效率更高
insert append delete replace
創(chuàng)建的同時先準備好6個字符的空間
StringBuilder sb = new StringBuilder(6);
append 在末尾追加
sb.append("I");
sb.append("Love");
sb.append("Android");
System.out.println(sb);
運行結(jié)果
ILoveAndroid
replace 替換
start and end
int start = sb.indexOf("Android");
int end = start + "Android".length();
sb.replace(start,end,"You");
System.out.println(sb);
運行結(jié)果
ILoveYou
reverse 反轉(zhuǎn)
sb.reverse();
System.out.println(sb);
運行結(jié)果
uoYevoLI