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

本文首發於公衆號「AntDream」,歡迎微信搜索「AntDream」或掃描文章底部二維碼關注,和我一塊兒天天進步一點點bash

反轉

反轉最簡單的就是用StringBuilder和StringBuffer的reverse方法微信

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

左移和右移都有不少種方式來實現,這裏簡單介紹下三次反轉法來實現左移右移app

右移

/**
 * 右移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;
}
複製代碼

流程圖

左移

/**
 * 左移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;
}
複製代碼

流程圖


歡迎關注個人微信公衆號,和我一塊兒天天進步一點點!
複製代碼

AntDream
相關文章
相關標籤/搜索