使用C语言编写函数,将字符串循环右移n个字符,例如:abcdefg,循环右移3位,efgabcd。第一次看到这个题意时,发现如果n大于等于字符串长度应该怎么处理并不明确,并且也没有限制不能使用库函数,所以个人理解如下,如有不对,希望大家批评指正。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void move_right_str(char *pStr, int n)
{
if ((pStr == NULL) || (n <= 0)) {
return;
}
int nLen = strlen(pStr);
if (n >= nLen) {
//原先此处本意是直接return,但是看到有人这么理解,反正我是没能理解
n = n % nLen;
}
char* pHead = (char*)malloc(n * sizeof(char));
char* pTail = (char*)malloc((nLen - n) * sizeof(char));
memset(pHead, 0 ,sizeof(pHead));
memset(pTail, 0, sizeof(pTail));
memcpy(pHead, pStr + nLen - n, n);
memcpy(pTail, pStr, nLen - n);
memcpy(pStr, pHead, n);
memcpy(pStr + n , pTail, nLen - n);
return;
}
int main()
{
//abcdefg --> efgabcd
char szBuf[32] = { 0 };
strcpy(szBuf, "abcdefg");
move_right_str(szBuf, 3);
printf("szBuf = [%s]\n", szBuf);
return 0;
}