编写一个函数,作用是把一个char组成的字符串循环右移n个。比如原来是“abcdefghi”如果n=2,移位后应该是“hiabcdefgh”
view plaincopy to clipboardprint?
bool moveToRightNSteps(char * start, unsigned int n)
{
if( (start == NULL)) return false;
unsigned int length = strlen(start);
if(length != 0)
{
// while n > string length, n%length to avoid repeat operation
n = n%length;
int m = length - n; // the starting m num should be moved to the end
char * tmp = new char[length + n + 1]; // temporary char array to help move string
if(tmp == NULL) return false;
//strcpy(tmp, start + m);
memcpy(tmp, start + m, n * sizeof(char));
//strcpy(tmp + n, start);
memcpy(tmp + n, start, m* sizeof(char));
//tmp[length] = '\0';
*(tmp + length) = '\0';
memcpy(start, tmp, length*sizeof(char));
delete [] tmp;
tmp = NULL;
}
return true;
}
阅读(2852) | 评论(0) | 转发(0) |