1. 程式人生 > >java字串左移右移

java字串左移右移

public class StringReversal {
    /**
     * 反轉字串(迴圈交換)
     * 其他字串反轉的方法
     * 1、java的api:StringBuffer的reverse方法
     * 2、利用棧的特性(先進後出)
     * 3、反向遍歷字串
     * @param from
     * @return
     */
    public static String reChange(String from){
        char[] froms = from.toCharArray();
        int length = froms.length;
        for
(int i = 0; i < length/2; i++){ char temp = froms[i]; froms[i] = froms[length - 1 -i]; froms[length - 1 -i] = temp; } return String.valueOf(froms); } /** * 迴圈左移index位字串 * 思想:先部分反轉,後整體反轉 * @param from * @param index * @return
*/
public static String leftMoveIndex(String from,int index){ String first = from.substring(0,index); String second = from.substring(index); first = reChange(first); second = reChange(second); from = first + second; from = reChange(from); return
from; } /** * 迴圈右移index位字串 * 思想:先整體反轉,後部分反轉 * @param from * @param index * @return */ public static String rightMoveIndex(String from,int index){ from = reChange(from); String first = from.substring(0,index); String second = from.substring(index); first = reChange(first); second = reChange(second); from = first + second; return from; } public static void main(String[] args) { String leftString = "abcdefg"; System.out.println("左移2位字串結果:"+leftMoveIndex(leftString,2)); String rightString = "abcdefg"; System.out.println("右移2位字串結果:"+rightMoveIndex(rightString,2)); } } 輸出結果:
左移2位字串結果:cdefgab
右移2位字串結果:fgabcde