#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*左旋*/
char move_steps(char *msg, int steps) {
int i = 0;
int len = strlen(msg);
steps = steps % len; //保證移動的位數在字符串長度範圍內
while (steps) {
char tmp = msg[0];
for (i = 0; i < len - 1; i++) {
msg[i] = msg[i + 1];
}
msg[i] = tmp;
steps--;
}
return msg;
}
/*右旋*/
char RightLoopMove(char *pStr, unsigned short steps)
{
int len = strlen(pStr);
steps = steps % len;
int i = 0;
while (steps) {
char tmp = *(pStr + len - 1);
for (i = len - 1; i > 0; i--) {//注意不要越界
*(pStr + i) = *(pStr + i - 1);
}
pStr[i] = tmp;
steps--;
}
return pStr;
}
int main()
{
char p[] = "abcdef";
//move_steps(p, 2);
RightLoopMove(p, 2);
printf("%s\n",p);
system("pause");
return 0;
}
字符串:左旋和右旋
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.