如何在C中向左或向右旋转给定的字符串?

C函数将字符串向右或向左旋转给定数字。 当角色根据方向旋转超过字符串的结尾或开头时,它应该环绕

给定一个字符串str ,它具有长度length和旋转量n

向左旋转相当于

 reverse(str, 0, n); reverse(str, n, length); reverse(str, 0, length); 

向右旋转相当于

 reverse(str, 0, length - n); reverse(str, length - n, length); reverse(str, 0, length); 

现在你只需要一个反向function。

更新:我想到了如何使用mod来让你总是根据n的符号在正确的方向上旋转。

例如

 int mod = n % length; if (mod != 0) { //if 0, don't rotate reverse(str, 0, mod); reverse(str, mod, length); reverse(str, 0, length); } 

经历各种情况

如果n == 5且长度= 10,则mod = 5

如果n == 16且长度= 10,则mod = 6 – 向左旋转16 =向左旋转6

如果n == 0且长度=任何东西,mod = 0

如果n == -1且长度= 10,则mod = 9 – 向右旋转1与向左旋转9相同

如果n == -15且长度= 9,则mod = 3 – 向右旋转15与向左旋转3相同

我会做这样的事情:

 void rot(char *buf, int len, int r) { char *temp=malloc(r>=0?r:-r); if(r>=0) { memcpy(temp, buf+len-r, r); memmove(buf+r, buf, len-r); memcpy(buf, temp, r); } else { memcpy(temp, buf, r); memmove(buf, buf+r, len-r); memcpy(buf+len-r, temp, r); } free(temp); } 

当然提供r

在数组C ++中移动元素

另外, http://www.cs.bell-labs.com/cm/cs/pearls/s02b.pdf

 #include  #include  #include  char* strrot (int offset, size_t size, const char *inStr); int main (int argc, const char * argv[]) { const char *rotStr = "rotateme"; size_t rotStrSize = strlen(rotStr); char *resultStr; resultStr = strrot(-3, rotStrSize, rotStr); printf("-3, %s\n", resultStr); free(resultStr); resultStr = strrot(2, rotStrSize, rotStr); printf("+2, %s\n", resultStr); free(resultStr); resultStr = strrot(11, rotStrSize, rotStr); printf("+11, %s\n", resultStr); free(resultStr); resultStr = strrot(0, rotStrSize, rotStr); printf("0, %s\n", resultStr); free(resultStr); resultStr = strrot(-11, rotStrSize, rotStr); printf("-11, %s\n", resultStr); free(resultStr); return 0; } char* strrot (int offset, size_t size, const char *inStr) { char *result = (char *)malloc(size * sizeof(char)); int trueOffset = size - (offset % size); int inIndex = trueOffset; int outIndex = 0; for (inIndex = trueOffset; inIndex < (int)size; inIndex++, outIndex++) { result[outIndex] = inStr[inIndex]; } for (inIndex = 0; inIndex < trueOffset; inIndex++, outIndex++) { result[outIndex] = inStr[inIndex]; } result[(int)size] = '\0'; return result; } 

结果:

 -3, atemerot +2, merotate +11, emerotat 0, rotateme -11, atemerot