基于三次反转思想的字符串左移右移问题
package zi4fu2chuan4; /* * 基于三次反转思想的字符串左移2位 * * */ import java.util.Scanner; public class xuan2zhuan4_001 { /*字符串反序函数 * 输入:待操作字符串 * 输出:该字符串的反序字符串 */ private static String reChange(String from) { char[] froms = from.toCharArray(); //创建一个字符串对象,并转换为字符串数组 int length = froms.length; //求出字符串数组的长度 for(int i = 0; i<length/2; i++) { //将字符串数组分成2部分,长度为奇数也无妨 char temp = froms[i]; //存储前半部分 froms[i] = froms[length -1 -i]; //将后半部分放到前半部分 froms[length - 1 - i] = temp; //将前半部分放到后半部分,完成 } return String.valueOf(froms); } /*字符串循环左移函数 * 功能:循环左移位index位字符串 * 输入:待操作字符串from, 左移位位数index * 思想:先部分反转,后整体反转 * */ public static String LeftMoveIndex(String from, int index){ String first = from.substring(0,index); //获取[0,index]位置上的子字符串 String second = from.substring(index); //获取从 index 到结束的子字符串 first = reChange(first); //将[0,index]位的字符串反序 second = reChange(second); //将剩余部分反序 from = first + second; //将两部分拼接到一起 from = reChange(from); //整体反转,得到循环左移的字符串 return from; } /* * 字符串循环右移函数 * * */ 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) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String str = sc.next(); System.out.println(str); System.out.println("左移2位字符串结果:"+LeftMoveIndex(str,2)); System.out.println("右移2位字符串结果:"+RightMoveIndex(str,2)); } } }