【Java实例学习】通过reverse将字符串反转,必须使用StringBuffer格式的字符串

 

new:生成一个新变量。

StringBuffer(String):将String变更为StringBuffer格式。

reverse:可以用来将字符反转,但是必须是StringBuffer格式。

toString:将其他格式变更为String格式。

//第1种写法:
public class Test2 {
    public static void main(String[] args) {
        System.out.println(new StringBuffer("Hello World!").reverse());
        //将字符串"Hello World!"变更为StringBuffer格式,并新生成1个临时字符串,并通过reverse进行反转
    }
}

//第2种写法:
public class Test2 {
    public static void main(String[] args) {
        StringBuffer Strb1= new StringBuffer("Hello World!").reverse();
        //相对于第1种写法,定义了1个Strb1。
        System.out.println(Strb1);
    }
}

//第3种写法:
public class Test2 {
    public static void main(String[] args) {
        String Str1="Hello World!";
        StringBuffer Strb1= new StringBuffer(Str1).reverse();
        //将字符串Str1变更为StringBuffer格式,并新生成1个StringBuffer格式的字符串Strb1,并进行反转
        Str1=Strb1.toString();
        //将StringBuffer格式的字符串Strb1,变更为String格式
        System.out.println(Str1);
    }
}

//第4种写法:相对于第3种写法,将toString写到了一起。
public class Test2 {
    public static void main(String[] args) {
        String Str1="Hello World!";
        String Str2= new StringBuffer(Str1).reverse().toString();
        System.out.println(Str2);
    }
}
/*
 * 运行结果如下:
 * !dlroW olleH
 * */
发布了63 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/woshiyigerenlaide/article/details/103700477