1. equals方法的作用
- 方法介紹
public boolean equals(String s) 比較兩個字符串內容是否相同、區分大小寫
- 示例代碼
public class StringDemo02 {public static void main(String[] args) {//構造方法的方式得到對象char[] chs = {'a', 'b', 'c'};String s1 = new String(chs);String s2 = new String(chs);//直接賦值的方式得到對象String s3 = "abc";String s4 = "abc";//比較字符串對象地址是否相同System.out.println(s1 == s2);System.out.println(s1 == s3);System.out.println(s3 == s4);System.out.println("--------");//比較字符串內容是否相同System.out.println(s1.equals(s2));System.out.println(s1.equals(s3));System.out.println(s3.equals(s4));}
}
2. 遍歷字符串案例
2.1. 案例需求
鍵盤錄入一個字符串,使用程序實現在控制臺遍歷該字符串
2.2. 直接遍歷字符串
public class Test2字符串直接遍歷 {public static void main(String[] args) {//兩個方法://charAt():會根據索引獲取對應的字符//length(): 會返回字符串的長度//1.鍵盤錄入一個字符串Scanner sc = new Scanner(System.in);System.out.println("請輸入字符串");String str = sc.next();System.out.println(str);//2.遍歷for (int i = 0; i < str.length(); i++) {//i 依次表示字符串的每一個索引//索引的范圍:0 ~ 長度-1//根據索引獲取字符串里面的每一個字符//ctrl + alt + V 自動生成左邊的接受變量char c = str.charAt(i);System.out.println(c);}}
}
3. substring
ps:一個參數的從那個索引截取到最后
截取后要用變量進行接收, 它對原來的字符串變量沒有影響
4. replace
package com.itheima.stringdemo;public class StringDemo12 {public static void main(String[] args) {//1.獲取到說的話String talk = "你玩的真好,以后不要再玩了,TMD";//2.把里面的敏感詞TMD替換為***String result = talk.replace("TMD", "***");//3.打印結果System.out.println(result);}
}
package com.itheima.stringdemo;public class StringDemo13 {public static void main(String[] args) {//1.獲取到說的話String talk = "你玩的真好,以后不要再玩了,TMD,CNM";//2.定義一個敏感詞庫String[] arr = {"TMD","CNM","SB","MLGB"};//3.循環得到數組中的每一個敏感詞,依次進行替換for (int i = 0; i < arr.length; i++) {talk = talk.replace(arr[i], "***");}//4.打印結果System.out.println(talk);}
}