字符串的相关方法
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);}
}