字符串操作:如何实现字符串的反转及替换?

1. 字符串操作反转:

  操作反转使用StringBuilder更为方便,StringBuilder可以在原始对象上进行更改,避免了不必要的内存开销,且快捷方便。

public static void main(String[] args) {
    StringBuilder sb = new StringBuilder();   //创建sb可变字符串对象
    sb.append("hello");  // 添加字符
    System.out.println("反转前的字符串是: "+sb);
    sb.reverse(); // 字符串反转方法
    System.out.println("反转后的字符串是: "+sb);
    }

输出结果:
    反转前的字符串是: hello
    反转后的字符串是: olleh

   

  使用String写字符串反转

    public static void main(String[] args) {
        String str = "hello";
        int length = str.length();
        char[] chars = new char[length];
        int num = 0;
        for (int i = length; i > 0; i--) {
            chars[num] = str.charAt(i - 1);
            num++;
        }
    System.out.println(String.valueOf(chars));
}

输出结果:
    olleh
 

 

 

2.  字符串操作替换:

    操作反转使用StringBuilder更为方便,StringBuilder可以在原始对象上进行更改,避免了不必要的内存开销,且快捷方便。

    public static void main(String[] args) {
        //public StringBuilder replace(int start, int end, String str)
        // 将从索引 start 到 end-1 位置的字符替换为指定的字符串 str
        StringBuilder sb = new StringBuilder();
        sb.append("Hello, World!");
        System.out.println("替换前的字符串是: " + sb);
        // 将从0索引开始到底2个索引位置,替换成x
        sb.replace(7, 12, "Java");
        System.out.println("替换后的字符串是: " + sb);
    }
输出结果:
    替换前的字符串是: Hello, World!
    替换后的字符串是: Hello, Java!

   

     使用String写字符串替换:

    public static void main(String[] args) {
        String str = "Hello, World!";
        String replace = str.replace("World!", "Java!");
        System.out.println(replace);
    }
输出结果:
    Hello, Java!

 

posted @ 2023-07-10 15:53  一只礼貌狗  阅读(432)  评论(0)    收藏  举报