java实现字符串的翻转功能

方法一

/**
     * 使用StringBuilder自带函数reverse()实现翻转
     */
    public static String strReverse(String str) {
        StringBuilder strResult  = new StringBuilder(str);
        StringBuilder reverse = strResult.reverse();
        return reverse.toString();
    }

方法二

/**
     * 使用for循环遍历方式取字符串最后一位字符进行拼接
     */
    public static String strReverse(String str) {
        String string="";
        for (int i=str.length()-1; i>=0; i--) {
            string = string+str.charAt(i);
        }
        return string;
    }

方法三

 /**
     * 使用双指针不断的向中间位移,同时交换对方的位置
     */
    public static String strReverse(String str) {
        //定义头指针和尾指针
       int startIndex = 0;
       int endIndex = str.length()-1;
       //将字符串转成char数组
       char[] chars = str.toCharArray();
       while (endIndex>startIndex) {
           //先将头指针位置的字符存储进临时变量
           char temp  = chars[startIndex];
           //双方交换位置
           chars[startIndex]= chars[endIndex];
           chars[endIndex]= temp;
           //头指针与尾指针向中间位移
           startIndex++;
           endIndex--;
       }
       return new String(chars);
    }

 

posted @ 2022-12-22 13:51  马革皮  阅读(249)  评论(0编辑  收藏  举报