字符串左旋,如 ABCD左旋一个字符得到BCDA ABCD左旋两个字符得到CDAB
整体思路:一个原始数组(如ABCD),另外创建一个双倍于原始数组的数组(如ABCDABCD),再根据要旋转的字符数(如2)从双倍数组输出原始字符串的个数(4),即在ABCDABCD中 从第三位的‘C’开始输出4位停止,相当与输出字符串数组 (AB CDAB CD)中的CDAB。
代码如下(环境:Visual Studio 2017)
// 实现一个函数,可以左旋字符串中的k个字符。
// ABCD左旋一个字符得到BCDA
// ABCD左旋两个字符得到CDAB
#include <stdio.h>
#include <windows.h>
#include <string.h>
#include <assert.h>
#pragma warning(disable:4996);
void LeftRotate(char str[], char D[], int len, int K)
{
assert(str);
assert(D);
K %= len;
char *d = D;
char *s = str;
while (*d)
{
d++;
}
while (*s)
{
*d++ = *s++;
}
while (len--)
{
printf("%c", *(D + (K++)));
}
printf("\n");
}
int main()
{
char str[] = "abcd123";
char data[64];
int value = 0;
int size = strlen(str);
strcpy(data,str);
printf("请输入一个数:");
scanf("%d", &value);
printf("%s\n", str);
LeftRotate(str, data, size, value);
system("pause");
return 0;
}