1、String類概述
· 字符串是由多個字符組成的一串數據(字符序列),也可以看成是一個字符數組。
· 字符串字符值“abc”也可以看成是一個字符串對象。
· 字符串是常量,一旦被賦值,就不能被改變。
2、構造方法
· public String():空構造。
· public String(byte[] bytes):把字節數組轉成字符串。
· public String(byte[] bytes,int offset,int length):把字節數組的一部分轉成字符串。
· public String(char[] value):把字符數組轉成字符串。
· public String(char[] value,int offset,int count):把字符數組一部分轉成字符串。
· public String(String original):把一個字符串常量轉成字符串。
字符串的方法
· public int length():返回此字符串的長度。
/** * · public String():空構造 * · public String(byte[] bytes):把字節數組轉成字符串 * · public String(byte[] bytes,int offset,int length):把字節數組的一部分轉成字符串 * · public String(char[] value):把字符數組轉成字符串 * · public String(char[] value,int offset,int count):把字符數組一部分轉成字符串 * · public String(String original):把一個字符串常量轉成字符串 */ public class StringDemo01 { public static void main(String[] args) { //public String():空構造 String str1 = new String(); System.out.println("str1:"+str1); System.out.println("str1.length:"+str1.length()); System.out.println("----------------------------"); //public String(byte[] bytes):把字節數組轉成字符串 byte[] bys = {97,98,99,100,126}; String str2 = new String(bys); System.out.println("str2:"+str2); System.out.println("str2.length:"+str2.length()); System.out.println("----------------------------"); //public String(byte[] bytes,int offset,int length):把字節數組的一部分轉成字符串 String str3 = new String(bys,2,3); System.out.println("str3:"+str3); System.out.println("str3.length:"+str3.length()); System.out.println("----------------------------"); //public String(char[] value):把字符數組轉成字符串 char[] c = {'a','b','c','愛','生','活'}; String str4 = new String(c); System.out.println("str4:"+str4); System.out.println("str4.length:"+str4.length()); System.out.println("----------------------------"); //public String(char[] value,int offset,int count):把字符數組一部分轉成字符串 String str5 = new String(c,3,3); System.out.println("str5:"+str5); System.out.println("str5.length:"+str5.length()); System.out.println("----------------------------"); //public String(String original):把一個字符串常量轉成字符串 String str6 = new String("hello world"); System.out.println("str6:"+str6); System.out.println("str6.length:"+str6.length()); System.out.println("----------------------------"); //字符串字面值"hello world"也可以看成是一個字符串對象。 String s7 = "hello world"; System.out.println("s7:"+s7); System.out.println("s7.length():"+s7.length()); } }
輸出結果:
str1:
str1.length:0
----------------------------
str2:abcd~
str2.length:5
----------------------------
str3:cd~
str3.length:3
----------------------------
str4:abc愛生活
str4.length:6
----------------------------
str5:愛生活
str5.length:3
----------------------------
str6:hello world
str6.length:11
----------------------------
s7:hello world
s7.length():11
1)字符串一旦被賦值就不能被改變,指的是字符串的值不能改變,但是字符串的引用可以改變。
/* * 字符串的特點:一旦被賦值,就不能改變。 */ public class StringDemo02{ public static void main(String[] args) { String s = "hello"; s += "world"; System.out.println("s:" + s); // helloworld } }
2)String初始化的兩種方法,直接賦值和創建對象的初始化過程是不相同的。直接賦值比較節省內存。
/* * String s = new String(“hello”)和String s = “hello”;的區別? * 有。前者會創建2個對象,后者創建1個對象或0個對象(如果方法區的字符串常量池有的話就不用創建對象)。 * * ==:比較引用類型比較的是地址值是否相同 * equals:比較引用類型默認也是比較地址值是否相同,而String類重寫了equals()方法,比較的是內容是否相同。 */ public class StringDemo03{ public static void main(String[] args) { String s1 = new String("hello"); String s2 = "hello"; System.out.println(s1 == s2); //false System.out.println(s1.equals(s2)); //true } }
String內存分配圖:
3)看程序寫結果
/* * 看程序寫結果 * 字符串如果是變量相加,先開空間,在拼接。 * 字符串如果是常量相加,是先加,然后在常量池找,如果有就直接返回,否則,就創建。 */ public class StringDemo04{ public static void main(String[] args) { String s1 = "hello"; String s2 = "world"; String s3 = "helloworld"; System.out.println(s3 == s1 + s2);// false System.out.println(s3.equals((s1 + s2)));// true System.out.println(s3 == "hello" + "world");// true System.out.println(s3.equals("hello" + "world"));// true // 通過反編譯看源碼,我們知道這里已經做好了處理。 // System.out.println(s3 == "helloworld"); // System.out.println(s3.equals("helloworld")); } }
3、String類的判斷功能
· boolean equals(Object obj):比較字符串的內容是否相同,區分大小寫
· boolean equalsIgnoreCase(String str):比較字符串的內容是否相同,忽略大小寫
· boolean contains(String str):判斷大字符串中是否包含小字符串
· boolean startsWith(String str):判斷字符串是否以某個指定的字符串開頭
· boolean endsWith(String str):判斷字符串是否以某個指定的字符串結尾
· boolean isEmpty():判斷字符串是否為空
3)練習題:字符串反轉
注意:
· 字符串內容為空和字符串對象為空是兩回事。內容為空指對象存在,但是沒有內容,但是對象為空是指引用。
· String s = "";能調用方法,內容為空
· String s = null;不能調用方法,空對象
/** * · boolean equals(Object obj):比較字符串的內容是否相同,區分大小寫 * · boolean equalsIgnoreCase(String str):比較字符串的內容是否相同,忽略大小寫 * · boolean contains(String str):判斷大字符串中是否包含小字符串 * · boolean startsWith(String str):判斷字符串是否以某個指定的字符串開頭 * · boolean endsWith(String str):判斷字符串是否以某個指定的字符串結尾 * · boolean isEmpty():判斷字符串是否為空 */ public class StringDemo05{ public static void main(String[] args) { // 創建字符串對象 String s1 = "helloworld"; String s2 = "helloworld"; String s3 = "HelloWorld"; //boolean equals(Object obj):比較字符串的內容是否相同,區分大小寫 System.out.println("equals:" + s1.equals(s2)); //true System.out.println("equals:" + s1.equals(s3)); //false System.out.println("-----------------------"); // boolean equalsIgnoreCase(String str):比較字符串的內容是否相同,忽略大小寫 System.out.println("equals:" + s1.equalsIgnoreCase(s2)); //true System.out.println("equals:" + s1.equalsIgnoreCase(s3)); //true System.out.println("-----------------------"); // boolean contains(String str):判斷大字符串中是否包含小字符串 System.out.println("contains:" + s1.contains("hello")); //true System.out.println("contains:" + s1.contains("hw")); //false System.out.println("-----------------------"); // boolean startsWith(String str):判斷字符串是否以某個指定的字符串開頭 System.out.println("startsWith:" + s1.startsWith("h")); //true System.out.println("startsWith:" + s1.startsWith("hello")); //true System.out.println("startsWith:" + s1.startsWith("world")); //false System.out.println("-----------------------"); // 練習:boolean endsWith(String str):判斷字符串是否以某個指定的字符串結尾 System.out.println("startsWith:" + s1.endsWith("d")); //true System.out.println("startsWith:" + s1.endsWith("world")); //ture System.out.println("startsWith:" + s1.endsWith("wor")); //false System.out.println("-----------------------"); // boolean isEmpty():判斷字符串是否為空。 System.out.println("isEmpty:" + s1.isEmpty()); //false String s4 = ""; String s5 = null; System.out.println("isEmpty:" + s4.isEmpty()); //true // s5對象都不存在,所以不能調用方法,空指針異常 System.out.println("isEmpty:" + s5.isEmpty()); // NullPointerException } }
1)練習題:模擬登陸,給三次機會,並提示還有幾次,登陸成功后進行玩猜數字游戲。
/** * * 模擬登錄,給三次機會,並提示還有幾次。如果登錄成功,就可以玩猜數字小游戲了。 * * 分析: * A:定義用戶名和密碼。已存在的。 * B:鍵盤錄入用戶名和密碼。 * C:比較用戶名和密碼。 * 如果都相同,則登錄成功 * 如果有一個不同,則登錄失敗 * D:給三次機會,用循環改進,最好用for循環。 */ public class StringDemo06{ public static void main(String[] args) { // 定義用戶名和密碼。已存在的。 String username = "admin"; String password = "admin"; // 給三次機會,用循環改進,最好用for循環。 for(int x = 0; x < 3; x++){ // 鍵盤錄入用戶名和密碼。 Scanner sc = new Scanner(System.in); System.out.println("請輸入用戶名:"); String name = sc.nextLine(); System.out.println("請輸入密碼:"); String pwd = sc.nextLine(); if (name.equals(username) && pwd.equals(password)){ System.out.println("登陸成功,開始玩猜數字游戲."); //猜數字游戲 GuessNumberGame.start(); break; }else{ if ((2-x) == 0){ System.out.println("賬號已凍結,請與管理員聯系"); }else{ System.out.println("登陸失敗,你還有"+(2-x)+"次機會"); } } } } }
public class GuessNumberGame { public GuessNumberGame() { } public static void start(){ int number = (int)(Math.random()*100)+1; while(true){ //鍵盤錄入數據 Scanner sc = new Scanner(System.in); System.out.println("請輸入你要猜的數據(1-100):"); int guessNumber = sc.nextInt(); if (guessNumber > number){ System.out.println("你猜的數據" + guessNumber + "大了"); }else if(guessNumber < number){ System.out.println("你猜的數據" + guessNumber + "小了"); }else { System.out.println("恭喜你,猜中了"); break; } } } }
4、String的獲取功能
· int length():獲取字符串的長度
· char charAt(int index):獲取指定索引位置的字符
· int indexOf(int ch):返回指定字符再次字符串中第一次出現處的索引
為什么這里參數是int類型,而不是char類型?
原因是:‘a’ 和 97 其實都可以代碼‘a’。
· int indexOf(String str):返回指定字符串再次字符串第一次出現處的索引
· int indexOf(int ch,int fromIndex):返回指定字符在此字符串中從指定位置后第一次出現處的索引
· int indexOf(String str,int fromIndex):返回指定字符串在此字符串中從指定位置后第一次出現處的索引
· String substring(int start):從指定位置開始獲取字符串,默認到末尾,包括start索引
· String substring(int start,int end):從指定位置開始到指定位置結束獲取字符串,包括start索引,不包括end索引
public class StringDemo07 { public static void main(String[] args) { //定義一個字符串對象 String s = "helloworld"; //int length():獲取字符串的長度 System.out.println("s.length:"+s.length()); //10 System.out.println("----------------------"); //char charAt(int index):獲取指定索引位置的字符 System.out.println("charAt(int index):"+s.charAt(7)); //'r' System.out.println("----------------------"); //int indexOf(int ch):返回指定字符再次字符串中第一次出現處的索引 System.out.println("indexOf(int ch):"+s.indexOf('l')); //2 System.out.println("----------------------"); //int indexOf(String str):返回指定字符串再次字符串第一次出現處的索引 System.out.println("indexOf(String str):"+s.indexOf("owo")); //4 System.out.println("----------------------"); //int indexOf(int ch,int fromIndex):返回指定字符在此字符串中從指定位置后第一次出現處的索引 System.out.println("indexOf(int ch,int fromIndex):"+s.indexOf('l',4)); //8 System.out.println("indexOf(int ch,int fromIndex):"+s.indexOf('k',4)); //-1 System.out.println("indexOf(int ch,int fromIndex):"+s.indexOf('l',40)); //-1 System.out.println("----------------------"); //int indexOf(String str,int fromIndex):返回指定字符串在此字符串中從指定位置后第一次出現處的索引 System.out.println("indexOf(String str,int fromIndex):"+s.indexOf("owo",4)); //4 System.out.println("indexOf(String str,int fromIndex):"+s.indexOf("kwl",4)); //-1 System.out.println("indexOf(String str,int fromIndex):"+s.indexOf("owo",40)); //-1 System.out.println("----------------------"); //String substring(int start):從指定位置開始獲取字符串,默認到末尾,包括start索引 System.out.println("substring(int start):"+s.substring(5)); //"world" System.out.println("----------------------"); //String substring(int start,int end):從指定位置開始到指定位置結束獲取字符串,包括start索引,不包括end索引 System.out.println("substring(int start,int end):"+s.substring(3,8)); //"lowor" System.out.println("substring(int start,int end):"+s.substring(0,s.length())); //"helloworld" System.out.println("----------------------"); } }
1)遍歷字符串中的每個字符
/* * 需求:統計一個字符串中大寫字母字符,小寫字母字符,數字字符出現的次數。(不考慮其他字符) * 舉例: * "Hello123World" * 結果: * 大寫字符:2個 * 小寫字符:8個 * 數字字符:3個 * * 分析: * 前提:字符串要存在 * A:定義三個統計變量 * bigCount=0 * smallCount=0 * numberCount=0 * B:遍歷字符串,得到每一個字符。 * length()和charAt()結合 * C:判斷該字符到底是屬於那種類型的 * 大:bigCount++ * 小:smallCount++ * 數字:numberCount++ * * 這道題目的難點就是如何判斷某個字符是大的,還是小的,還是數字的。 * ASCII碼表: * 0 48 * A 65 * a 97 * 雖然,我們按照數字的這種比較是可以的,但是想多了,有比這還簡單的 * char ch = s.charAt(x); * * if(ch>='0' && ch<='9') numberCount++ * if(ch>='a' && ch<='z') smallCount++ * if(ch>='A' && ch<='Z') bigCount++ * D:輸出結果。 * * 練習:把給定字符串的方式,改進為鍵盤錄入字符串的方式。 */ public class StringDem08 { public static void main(String[] args) { //定義一個字符串 String s = "Hello123World"; //定義三個統計變量 int bigCount = 0; int smallCount = 0; int numberCount = 0; //遍歷字符串,得到每一個字符 for(int x = 0; x < s.length(); x++){ char ch = s.charAt(x); //判斷該字符到底是屬於那種類型的 if (ch >= '0' && ch <= '9'){ numberCount ++; }else if (ch >= 'A' && ch <= 'Z'){ bigCount++; }else if(ch >= 'a' && ch < 'z'){ smallCount++; } } //輸出結果 System.out.println("大寫字母"+bigCount+"個"); System.out.println("小寫字母"+smallCount+"個"); System.out.println("數字"+numberCount+"個"); } }
5、String類的轉換功能
· byte[] getBytes():把字符串轉換成字節數組
· char[] toCharArray():把字符串轉換為字符數組
· static String valueOf(char[] chs):把字符數組轉換成字符串
· static String valueOf(int i):把int類型的數據轉成字符串
注意:String類的valueOf方法可以把任意類型的數據轉成字符串
· String toLowerCase():把字符串轉成小寫
· String toUpperCase():把字符串轉成大寫
· String concat(String str):把字符串拼接
public class StringDem09 { public static void main(String[] args) { // 定義一個字符串對象 String s = "JavaSE"; // byte[] getBytes():把字符串轉換為字節數組 byte[] bys = s.getBytes(); for(int x = 0; x < bys.length;x++){ System.out.println(bys[x]); } System.out.println("---------------------"); // char[] toCharArray():把字符串轉換為字符數組 char ch[] = s.toCharArray(); for(int x = 0; x < ch.length; x++){ System.out.println(ch[x]); } System.out.println("---------------------"); // static String valueOf(char[] chs):把字符數組轉成字符串 String s1 = String.valueOf(ch); System.out.println("s1:"+s1); System.out.println("---------------------"); // static String valueOf(int i):把int類型的數據轉成字符串 int i = 100; String s2 = String.valueOf(i); System.out.println("s2:"+s2); System.out.println("---------------------"); // String toLowerCase():把字符串轉成小寫 System.out.println("toLowerCase():"+s.toLowerCase()); System.out.println("s:"+s); System.out.println("---------------------"); // String toUpperCase():把字符串轉成大寫 System.out.println("toUpperCase():"+s.toUpperCase()); System.out.println("---------------------"); // String concat(String str):把字符串拼接 String s3 = "hello"; String s4 = "world"; String s5 = s3 +s4; String s6 = s3.concat(s4); System.out.println("s5:"+s5); System.out.println("s6:"+s6); } }
輸出結果:
74
97
118
97
83
69
---------------------
J
a
v
a
S
E
---------------------
s1:JavaSE
---------------------
s2:100
---------------------
toLowerCase():javase
s:JavaSE
---------------------
toUpperCase():JAVASE
---------------------
s5:helloworld
s6:helloworld
1)練習題:把一個字符串的首字母轉成大寫,其余為小寫。(只考慮英文大小寫字母字符)
public class StringDemo10 { public static void main(String[] args) { // 定義一個字符串 String s = "helloWORLD"; // 先獲取第一個字符 String s1 = s.substring(0,1); // 獲取除了第一個字符以外的字符 String s2 = s.substring(1); // 把A轉成大寫 String s3 = s1.toUpperCase(); // 把B轉成小寫 String s4 = s2.toLowerCase(); // C拼接D String s5 = s3.concat(s4); System.out.println("s5:"+s5); // 優化后的代碼 // 鏈式編程 String result = s.substring(0,1).toUpperCase().concat(s.substring(1).toLowerCase()); System.out.println("result:"+result); }
6、String類的其他功能
A:
替換功能
·
String replace(char old,char new)
·
String replace(String old,String new)
B:
去除字符串兩空格
·
String trim()
C:
按字典順序比較兩個字符串
·
int compareTo(String str)
·
int compareToIgnoreCase(String str)
public class StringDemo11 { public static void main(String[] args) { // 替換功能 String s1 = "helloworld"; String s2 = s1.replace('l', 'k'); String s3 = s1.replace("owo", "ak47"); System.out.println("s1:" + s1); //s1:helloworld System.out.println("s2:" + s2); //s2:hekkoworkd System.out.println("s3:" + s3); //s3:hellak47rld System.out.println("---------------"); // 去除字符串兩空格 String s4 = " hello world "; String s5 = s4.trim(); System.out.println("s4:"+s4+"---"); //s4: hello world --- System.out.println("s5:"+s5+"---"); //s5:hello world--- // 按字典順序比較兩個字符串 String s6 = "hello"; String s7 = "hello"; String s8 = "abc"; String s9 = "xyz"; System.out.println(s6.compareTo(s7)); //0 System.out.println(s6.compareTo(s8)); //7 System.out.println(s6.compareTo(s9)); //-16 } }
1)String類的compareTo方法的源碼解析
private final char value[]; 字符串會自動轉換為一個字符數組。 public int compareTo(String anotherString) { //this -- s1 -- "hello" //anotherString -- s2 -- "hel" int len1 = value.length; //this.value.length--s1.toCharArray().length--5 int len2 = anotherString.value.length;//s2.value.length -- s2.toCharArray().length--3 int lim = Math.min(len1, len2); //Math.min(5,3); -- lim=3; char v1[] = value; //s1.toCharArray() char v2[] = anotherString.value; //char v1[] = {'h','e','l','l','o'}; //char v2[] = {'h','e','l'}; int k = 0; while (k < lim) { char c1 = v1[k]; //c1='h','e','l' char c2 = v2[k]; //c2='h','e','l' if (c1 != c2) { return c1 - c2; } k++; } return len1 - len2; //5-3=2; } //ceshi String s1 = "hello"; String s2 = "hel"; System.out.println(s1.compareTo(s2)); // 2
2)練習題:把數組中的數據按照指定格式拼接成一個字符串
/** * * 需求:把數組中的數據按照指定個格式拼接成一個字符串 * 舉例: * int[] arr = {1,2,3}; * 輸出結果: * "[1, 2, 3]" * 分析: * A:定義一個字符串對象,只不過內容為空 * B:先把字符串拼接一個"[" * C:遍歷int數組,得到每一個元素 * D:先判斷該元素是否為最后一個 * 是:就直接拼接元素和"]" * 不是:就拼接元素和逗號以及空格 * E:輸出拼接后的字符串 * * 把代碼用功能實現。 */ public class StringDemo12 { public static void main(String[] args) { // 前提是數組已經存在 int[] arr = { 1, 2, 3 }; // 寫一個功能,實現結果 String resutl = arrayToString(arr); System.out.println("最終結果是:"+resutl); } /* * 兩個明確: 返回值類型:String 參數列表:int[] arr */ public static String arrayToString(int[] arr){ // 定義一個字符串 String s = ""; // 先把字符串拼接一個"[" s += "["; // 遍歷int數組,得到每一個元素 for(int x = 0; x < arr.length; x++){ // 先判斷該元素是否為最后一個 if (x == arr.length-1){ // 就直接拼接元素和"]" s += arr[x]; s += "]"; }else{ // 就拼接元素和逗號以及空格 s += arr[x]; s += ", "; } } return s; } }
輸出結果:
最終結果是:[1, 2, 3]
/** * 字符串反轉 * 舉例:鍵盤錄入”abc” * 輸出結果:”cba” * <p/> * 分析: * A:鍵盤錄入一個字符串 * B:定義一個新字符串 * C:倒着遍歷字符串,得到每一個字符 * a:length()和charAt()結合 * b:把字符串轉成字符數組 * D:用新字符串把每一個字符拼接起來 * E:輸出新串 */ public class StringDemo13 { public static void main(String[] args) { // 鍵盤錄入一個字符串 Scanner sc = new Scanner(System.in); System.out.println("請輸入一個字符串:"); String line = sc.nextLine(); //調用字符串反轉方法 String s = myReverse(line); System.out.println("實現功能后的結果是:" + s); } public static String myReverse(String s) { // 定義一個新字符串 String result = ""; // 把字符串轉成字符數組 char[] ch = s.toCharArray(); // 倒着遍歷字符串,得到每一個字符 for(int x = ch.length-1; x >=0; x--){ // 用新字符串把每一個字符拼接起來 result += ch[x]; } return result; } }
輸出結果:
請輸入一個字符串:
hello world
實現功能后的結果是:dlrow olleh
4)統計大串中小串出現的次數(這段程序考慮得可能不是很周全,如果查找的字符串是有重復的,比如小字符串是aoa,大字符串是aoaoaoa,我覺得結果是3,但是這段程序的結果應該是2)。
/** * 統計大串中小串出現的次數 * 舉例: * 在字符串"woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun" * 結果: * java出現了5次 * * 分析: * 前提:是已經知道了大串和小串。 * * A:定義一個統計變量,初始化值是0 * B:先在大串中查找一次小串第一次出現的位置 * a:索引是-1,說明不存在了,就返回統計變量 * b:索引不是-1,說明存在,統計變量++ * C:把剛才的索引+小串的長度作為開始位置截取上一次的大串,返回一個新的字符串,並把該字符串的值重新賦值給大串 * D:回到B */ public class StringDemo14 { public static void main(String[] args) { // 定義大串 String maxString = "woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun"; // 定義小串 String minString = "java"; // 寫功能實現 int count = getCount(maxString, minString); System.out.println("Java在大串中出現了:" + count + "次"); } public static int getCount(String maxString, String minString){ // 定義一個統計變量,初始化值是0 int count = 0; // 先在大串中查找一次小串第一次出現的位置 int index = maxString.indexOf(minString); // 索引不是-1,說明存在,統計變量++ while(index != -1){ count++; // 把剛才的索引+小串的長度作為開始位置截取上一次的大串,返回一個新的字符串,並把該字符串的值重新賦值給大串 int startIndex = index + minString.length(); maxString = maxString.substring(startIndex); // 繼續查 index = maxString.indexOf(minString); } return count; } /* * 簡潔版 * int index; * while((index = maxString.indexOf(minString)) != -1 ){ * count++; * maxString = maxString.substring(index + minString.length); * } * */ }