本文首发于公众号“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;
}
左移
/**
* 左移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;
}
欢迎关注我的微信公众号,和我一起每天进步一点点!