Java零基础学习17:字符串练习

编写博客目的:本系列博客均根据B站黑马程序员系列视频学习和编写目的在于记录自己的学习点滴,方便后续回忆和查找相关知识点,不足之处恳请各位有缘的朋友指正。

一、敏感词替换

package com.itheima;

public class StringDemo8 {
    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;

public class StringDemo8 {
    public static void main(String[] args) {
        // 1. 获取到说的话
        String talk = "你玩的真好,以后不要再玩了,TMD";

        // 2. 敏感词替换
        String[] arr = {"TMD","CNM","SB","MLGB"};
        
        // 3. 替换敏感词TMD为***
        for (int i = 0; i < arr.length; i++) {
            talk = talk.replace(arr[i],"***");
        }

        // 4. 打印结果
        System.out.println(talk);
    }
}

二、StringBuilder对象处理

package com.itheima;

public class StringDemo10 {
    public static void main(String[] args) {
        // 1. 创建对象
        StringBuilder sb = new StringBuilder();

        // 2. 添加字符串
        sb.append("aaa");
        sb.append("bbb");
        sb.append("ccc");

        System.out.println(sb);

        // 3. 把对象变回字符串
        String str = sb.toString();
        System.out.println(str);
    }
}

三、对称字符串

键盘接受一个字符串,判断字符串是否为对称字符串

package com.itheima;

import java.util.Scanner;

public class StringDemo11 {
    public static void main(String[] args) {
        // 1. 键盘录入一个字符串
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串");
        String str = sc.next();

        // 2. 反转键盘录入的字符串
        String result = new StringBuilder().append(str).reverse().toString();

        // 3. 比较
        if(str.equals(result)){
            System.out.println("输入字符串是对称的");
        }else {
            System.out.println("输入字符串不是对称的");
        }
    }
}

四、StringJoiner

package com.itheima;

import java.util.StringJoiner;

public class StringDemo12 {
    public static void main(String[] args) {
        int[] arr = {1,2,3};
        StringJoiner sj = new StringJoiner(",","[","]");
        for (int i = 0; i < arr.length; i++) {
            sj.add(arr[i] + "");
        }
        System.out.println(sj);
    }
}

你可能感兴趣的:(学习)