字符串转换方法

发布时间 2023-04-19 18:35:22作者: harper886

字符串转换方法

字符串转换函数

  1. 转换为字符数组

  2. 转换为字节数组

  3. 将旧字符串替换为新字符串

image-20230419175720566

代码示例

public class Demo02 {
    public static void main(String[] args) {
        //替换为字符数组
        //使用toCharArray方法
        char[] chars = "abcdef".toCharArray();
        System.out.println(chars.length);
        for (int i = 0; i < chars.length; i++) {
            System.out.println(chars[i]);
        }
        //替换为字节数组
        //使用getBytes方法
        byte[] bytes = "ABC".getBytes();
        for (int i = 0; i < bytes.length; i++) {
            System.out.println(bytes[i]);
        }
        //字符串替换函数
        String str1 = "how how how how";
        System.out.println(str1);
        String str2 = str1.replace("o", "&");
        System.out.println(str2);
        String str3 = str1.replace("ow", "%");
        System.out.println(str3);


    }
}