将字符串类型的数据反转输出

这是一个老面试题了,可能因为有段时间没写代码的原因吧,竟然被问懵逼了,真是可耻。

String类型数据是java中最长使用的数据之一,区别去其他基础类型的数据(byte、short、int、long、float、double、char、boolean),String类型的数据是引用类型的。

String相关类继承关系:

言归正传:

public class FlashBackTest {

    public static void main(String[] args) {
        String val = method1("123456789");
        System.out.println("方法一:"+val);
        String val2 = method2(val);
        System.out.println("方法二:"+val2);
        String val3 = method3(val2);
        System.out.println("方法三:"+val3);
        String val4 = method4(val3);
        System.out.println("方法四:"+val4);
    }
    //方法一
    public static String method1(String str){
        char [] strArr = str.toCharArray();
        for(int i=0,j=strArr.length-1;i<j;i++,j--){
            char tmp = strArr[i];
            strArr[i] = strArr[j];
            strArr[j] = tmp;
        }
        return new String(strArr);
    }

    //方法二
    public static String method2(String str){
        StringBuilder sbr = new StringBuilder(str);
        StringBuilder val = sbr.reverse();
        return val.toString();
    }
    //方法三
    public static String method3(String str){
        String num = "";
        for(int i = str.length()-1;i>=0;i--){
            num = num + str.charAt(i);
        }
        return num;
    }
    //方法四
    public static String method4(String str){
        StringBuilder stringBuilder = new StringBuilder();
        for(int i = str.length()-1;i>=0;i--){
            stringBuilder.append(str.charAt(i));
        }
        return stringBuilder.toString();
    }

}

方法一:

    这种方法类似于二分查找算法,找到字符串的中间值,两两互换;

方法二:

    这种方法借助于StringBuilder类提供的reverse()方法进行直接输出反转后的值,StringBuilder同样也可以得到相应的效果,但是reverse方法并不是由StringBuilder和StringBuilder提供的,而是由他们的父类AbstractStringBuilder的抽象类来具体的实现的;

/**
 * Causes this character sequence to be replaced by the reverse of
 * the sequence. If there are any surrogate pairs included in the
 * sequence, these are treated as single characters for the
 * reverse operation. Thus, the order of the high-low surrogates
 * is never reversed.
 *
 * Let <i>n</i> be the character length of this character sequence
 * (not the length in {@code char} values) just prior to
 * execution of the {@code reverse} method. Then the
 * character at index <i>k</i> in the new character sequence is
 * equal to the character at index <i>n-k-1</i>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值