Java练习String反转(自己方法编写)

如有错误,请指出

public class StringReverse {
    public static void main(String[] args) {
        String str = "abcdefghijk";
//        char s = str.charAt(0);
//        System.out.println(s);
        System.out.println(str);
        //try-catch快捷键CTRL+alt+t
        try {
            reverse(str, 1, 72);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return;
        }

    }
    /*
    思路分析
    (1)先把方法确定
    (2)可以把String转成char[]数组, 因为char[],的元素可以交换
     */
    public static String reverse(String str, int start, int end){

//        //对输入的数字做一个防护机制
        //缺点,有想不到的错误情况,会漏掉某些错误情况
//        if (end >= str.length() || start < 0){
//            System.out.println("您输入的范围有误");
//            System.exit(0);
//        }

        //老师技巧
        //(1)写出正确的情况
        //(2)然后取反即可
        if (!(str != null && end > start && start >= 0 && end < str.length())){
            System.out.println("您输入的范围有误");
            throw new RuntimeException("输入异常");
        }


        //方法代码
        char temp = ' ';
        char[] replaces = new char[str.length()];
        char[] chars = new char[str.length()];
        for (int i = 0; i < str.length(); i++) {//将String保存到char[]数组中
            chars[i] = str.charAt(i);
            replaces[i] = str.charAt(i);
        }
        //[a, b, c, d, e, f]
        for (int i = start, j = end; i <= end; i++, j--) {//交换字符
            temp = chars[i];
            chars[i] = replaces[j];
            replaces[j] = temp;
        }
        //清空字符串String
        str = "";
        for (int i = 0; i < chars.length; i++) {
            str += chars[i];
        }

        System.out.println(str);
        System.out.println(Arrays.toString(replaces));
        System.out.println(Arrays.toString(chars));
        System.out.println("======");
        return str;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值