Android字符串反转、左移和右移

  1. 云栖社区>
  2. 博客>
  3. 正文

Android字符串反转、左移和右移

xxq2dream 2019-06-22 10:14:56 浏览59
展开阅读全文

本文首发于公众号“AntDream”,欢迎微信搜索“AntDream”或扫描文章底部二维码关注,和我一起每天进步一点点

反转

反转最简单的就是用StringBuilder和StringBuffer的reverse方法

private String reverseString(String original) {
        StringBuilder builder = new StringBuilder();
        builder.append(original);
        return builder.reverse().toString();
    }

左移和右移都有很多种方式来实现,这里简单介绍下三次反转法来实现左移右移

右移

/**
 * 右移index位
 * @param from
 * @param index
 * @return
 */
private String rightMoveIndex(String from, int index) {
    from = reverseString(from);
    String first = from.substring(0,index);
    String second = from.substring(index);
    first = reverseString(first);
    second = reverseString(second);
    from = first + second;
    return from;
}

image

左移

/**
 * 左移index位
 * @param from
 * @param index
 * @return
 */
private String leftMoveIndex(String from, int index) {
    from = reverseString(from);
    String first = from.substring(0,from.length()-index-1);
    String second = from.substring(from.length() -index);
    first = reverseString(first);
    second = reverseString(second);
    from = first + second;
    return from;
}

image


                       欢迎关注我的微信公众号,和我一起每天进步一点点!

AntDream

网友评论

登录后评论
0/500
评论
xxq2dream
+ 关注