循环移位
将字符串进行循环移位
abcdefg-----defgabc
[cpp]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 100
//方法1
void LoopMove1(char *pStr, int steps)
{
int n = strlen(pStr)-steps;
char tmp[MAX_LEN];
strcpy (tmp, pStr+steps);
strcpy (tmp+n, pStr);
*(tmp+strlen(pStr)) = '\0';
strcpy( pStr, tmp );
}
//方法2
void LoopMove2(char *pStr, int steps)
{
int n = strlen( pStr )-steps;
char tmp[MAX_LEN];
memcpy(tmp, pStr+steps, n);
memcpy(tmp+n, pStr, steps );
memcpy(pStr, tmp, strlen(pStr));
}
//方法3
void reverse(char *begin, char *end)
{
char tmp=0;
while(begin < end)
{
tmp = *begin;
*begin = *end;
*end = tmp;
begin++;
end--;
}
}
void LoopMove3(char *pStr, int step)
{
int n=strlen(pStr);
reverse(pStr,pStr+step-1);
reverse(pStr+step,pStr+n-1);
reverse(pStr,pStr+n-1);
}
void main()
{
char src[] = "abcdefg";
LoopMove1(src,1);
puts(src);
LoopMove2(src,2);
puts(src);
LoopMove3(src,3);
puts(src);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 100
//方法1
void LoopMove1(char *pStr, int steps)
{
int n = strlen(pStr)-steps;
char tmp[MAX_LEN];
strcpy (tmp, pStr+steps);
strcpy (tmp+n, pStr);
*(tmp+strlen(pStr)) = '\0';
strcpy( pStr, tmp );
}
//方法2
void LoopMove2(char *pStr, int steps)
{
int n = strlen( pStr )-steps;
char tmp[MAX_LEN];
memcpy(tmp, pStr+steps, n);
memcpy(tmp+n, pStr, steps );
memcpy(pStr, tmp, strlen(pStr));
}
//方法3
void reverse(char *begin, char *end)
{
char tmp=0;
while(begin < end)
{
tmp = *begin;
*begin = *end;
*end = tmp;
begin++;
end--;
}
}
void LoopMove3(char *pStr, int step)
{
int n=strlen(pStr);
reverse(pStr,pStr+step-1);
reverse(pStr+step,pStr+n-1);
reverse(pStr,pStr+n-1);
}
void main()
{
char src[] = "abcdefg";
LoopMove1(src,1);
puts(src);
LoopMove2(src,2);
puts(src);
LoopMove3(src,3);
puts(src);
}
补充:软件开发 , C++ ,