编程语言
首页 > 编程语言> > 字符串倒序输出-java版

字符串倒序输出-java版

作者:互联网

法一(拆分字符数组):

public class MyTest {
    public static void main(String[] args) {

        String s = "abbdfaadqwedqfdad";
        //字符串转化为字符数组
        char[] charArray = s.toCharArray();

        char[] chars = new char[s.length()];

        for (int i = 0; i < charArray.length; i++) {
            chars[i] = charArray[charArray.length - i - 1];
        }
        //直接利用字符串的构造方法将字符数组转化为字符串
        String s1 = new String(chars);

        System.out.println(s1);
    }
}

法二(利用字符串特性):

public class MyTest {
   public static void main(String[] args) {

        String s = "abbdfaadqwedqfdad";
        String s2 = "";

        for (int i = s.length() - 1; i >= 0; i--) {
            s2 += s.charAt(i);
        }
        System.out.println(s2);
    }
    }
}

法三(StringBuilder的reverse()方法):

    public static void main(String[] args) {

        String s = "abbdfaadqwedqfdad";
        StringBuilder stringBuilder = new StringBuilder(s);

        stringBuilder.reverse();

        String s1 = stringBuilder.toString();

        System.out.println(s1);
    }

标签:java,String,s1,charArray,length,字符串,倒序,public
来源: https://blog.csdn.net/U12Euphoria/article/details/123082670