1. 創建String對象的常用方法
(1) String s1 = "mpptest"
(2) String s2 = new String();
(3) String s3 = new String("mpptest")
2. String中常用的方法,用法如圖所示,具體問度娘
3. 三個方法的使用: lenth() substring() charAt()
package com.mpp.string; public class StringDemo1 { public static void main(String[] args) { //定義一個字符串"晚來天欲雪 能飲一杯無" String str = "晚來天欲雪 能飲一杯無"; System.out.println("字符串的長度是:"+str.length()); //字符串的雪字打印輸出 charAt(int index) System.out.println(str.charAt(4)); //取出子串 天欲 System.out.println(str.substring(2)); //取出從index2開始直到最后的子串,包含2 System.out.println(str.substring(2,4)); //取出index從2到4的子串,包含2不包含4 顧頭不顧尾 } }
4. 兩個方法的使用,求字符或子串第一次/最后一次在字符串中出現的位置: indexOf() lastIndexOf()
package com.mpp.string; public class StringDemo2 { public static void main(String[] args) { String str = new String("趙客縵胡纓 吳鈎胡纓霜雪明"); //查找胡在字符串中第一次出現的位置 System.out.println("\"胡\"在字符串中第一次出現的位置:"+str.indexOf("胡")); //查找子串"胡纓"在字符串中第一次出現的位置 System.out.println("\"胡纓\"在字符串中第一次出現的位置"+str.indexOf("胡纓")); //查找胡在字符串中最后一次次出現的位置 System.out.println(str.lastIndexOf("胡")); //查找子串"胡纓"在字符串中最后一次出現的位置 System.out.println(str.lastIndexOf("胡纓")); //從indexof為5的位置,找第一次出現的"吳" System.out.println(str.indexOf("吳",5)); } }
5. 字符串與byte數組間的相互轉換
package com.mpp.string; import java.io.UnsupportedEncodingException; public class StringDemo3 { public static void main(String[] args) throws UnsupportedEncodingException { //字符串和byte數組之間的相互轉換 String str = new String("hhhabc銀鞍照白馬 颯沓如流星"); //將字符串轉換為byte數組,並打印輸出 byte[] arrs = str.getBytes("GBK"); for(int i=0;i<arrs.length;i++){ System.out.print(arrs[i]); } //將byte數組轉換成字符串 System.out.println(); String str1 = new String(arrs,"GBK"); //保持字符集的一致,否則會出現亂碼 System.out.println(str1); } }
6. 等於運算符和equals之間的區別:
引用指向的內容和引用指向的地址
package com.mpp.string; public class StringDemo5 { public static void main(String[] args) { String str1 = "mpp"; String str2 = "mpp"; String str3 = new String("mpp"); System.out.println(str1.equals(str2)); //true 內容相同 System.out.println(str1.equals(str3)); //true 內容相同 System.out.println(str1==str2); //true 地址相同 System.out.println(str1==str3); //false 地址不同 } }
7. 字符串的不可變性
String的對象一旦被創建,則不能修改,是不可變的
所謂的修改其實是創建了新的對象,所指向的內存空間不變
上圖中,s1不再指向imooc所在的內存空間,而是指向了hello,imooc