/********************************************************************** * RightMove.cpp * Compiler: GCC,VS,VC6.0 win32 * Author:WK ************************************************************************/ void RightLoopMove(char *pStr, unsigned short steps) { int len = strlen(pStr); steps %= len; //可以增加程序健壮性,对于较大的移动可以进行长度取余,减少不必要的循环移动 if(0 ==steps ) return; char tmp;//只借用一个空间 while(steps > 0) { tmp = pStr[len-1]; for(int i=len-1; i>0; --i) { pStr[i] = pStr[i-1]; } pStr[0] = tmp; steps--; } } void main() { char str[] = "abcdefghi"; cout<<str<<endl; RightLoopMove(str,2); cout<<str<<endl; } /*借用空间较大,并且借助了库函数,程序效率不高 void RightLoopMove(char *pStr, unsigned short steps) { int len = strlen(pStr); steps %= len; if(steps == 0) return; char *data = (char *)malloc(sizeof(char)*len+1); strcpy(data,pStr+(len-steps)); strncat(data,pStr,len-steps); strcpy(pStr,data); free(data); } */ void main() { char str[] = "abcdefghi"; cout<<str<<endl; RightLoopMove(str,901); cout<<str<<endl; }
时间: 2024-10-11 08:19:42