读《程序员编程艺术》之自造Java版本-----字符串左移

来源:互联网 发布:centos搭建mc服务器 编辑:程序博客网 时间:2024/05/22 04:23

在本程序中使用了最简单的按位循环转移法,虽然思想简单,但是在实现的过程中还是遇到了一些问题,经过调试最终解决。
/*
* 实现了字符串的左旋转,采用暴力法
* 在输入时,采用in.next以字符串的形式输出,后变化为char
*/
package chatacterShift;

import java.util.Scanner;

public class CharacterShift {
char l[]=new char [5];//字符串长度
int m;//旋转次数
public void GetChar() {
char ll[]=new char [5];
int mm;
String str;
Scanner in =new Scanner(System.in);
System.out.println(“请输入循环的次数”);
mm=in.nextInt();
System.out.println(“请输入要循环的字符串”);
str=in.next();
ll=str.toCharArray();
m=mm;
l=ll;
}
public void ChangeOne() {
char cache;
cache=l[l.length-1];
for (int i = l.length-1; i >0; i–) {
l[i]=l[i-1];
}
l[0]=cache;
}
public void Out() {
for (int i = 0; i < l.length; i++) {
System.out.println(l[i]);//输出字符串
}
}
public static void main(String[] args){
CharacterShift Character=new CharacterShift();
Character.GetChar();
while (Character.m>0) {
Character.ChangeOne();
Character.m–;
}
Character.Out();
}
}

实验结果如下:
请输入K的值
2
输出结果为:
20 9 15 8 2 6 10 5 7 输出结果为:
2 5

0 0
原创粉丝点击