比如原来是“abcdefghij”,如果n=2,移位后应该是“hiabcdefgh”
#include <iostream>
#include <string.h>
using namespace std;
void LoopMove(char *pStr, int steps)
{
char *temp;
int n = strlen(pStr) - steps;
if(NULL==(temp = (char *)malloc((strlen(pStr)+1+steps)*sizeof(char))))
throw "分配内存失败!";
strcpy(temp, pStr+n);
strcpy(temp+steps, pStr);
*(temp + strlen(pStr)) = '\0';
strcpy(pStr, temp);
free(temp);
}
void LoopMove1(char *pStr, int steps)
{
char *temp;
int n = strlen(pStr) - steps;
if(NULL==(temp = (char *)malloc((strlen(pStr)+1+steps)*sizeof(char))))
throw "分配内存失败!";
memcpy(temp, pStr+n, steps);
memcpy(temp+steps, pStr, n);
memcpy(pStr, temp, strlen(pStr));
free(temp);
}
int main()
{
int step;
char str1[20];
memset(str1, 0, sizeof(str1));
scanf("%s", str1);
scanf("%d", &step);
// 使用strcpy库函数操作
// LoopMove(str1, step);
// 使用memcpy库函数操作
LoopMove1(str1, step);
printf("%s\n", str1);
return 0;
}