用c语言实现字母移位,【C语言】实现字符串右移位函数

请实现字符串右移位函数,比如:"abcdefghi"循环右移2位就是"hiabcdefg"。

函数原型:void RightLoopMove(char *str, unsigned short steps)

函数参数说明:

pStr: Point to a '\0' terminated string.

steps: The rotate shift numbers.

①暴力移位法:

#include #include #include void RightLoopMove(char *pStr, unsigned short steps)

{

int i = 0;

int len = strlen(pStr);

assert(pStr);

for (i = 0; i < steps; i++)

{

char *pend = pStr + len - 1;

char tmp = *(pStr + len - 1);

while (pStr <= pend)

{

*pend = *(pend - 1);

pend--;

}

*pStr = tmp;

}

}

int main()

{

char str[] = "abcdef";

RightLoopMove(str, 2);

printf("%s\n", str);

getchar();

return 0;

}

用c语言实现字母移位,【C语言】实现字符串右移位函数_第1张图片

②三步翻转法:

#include #include #include void StrReverse(char *pStart, char *pEnd)

{

assert(pStart);

assert(pEnd);

while (pStart < pEnd)

{

char tmp = *pStart;

*pStart = *pEnd;

*pEnd = tmp;

pStart++;

pEnd--;

}

}

void RightLoopMove(char *pStr, unsigned short steps)

{

int len = strlen(pStr);

assert(pStr);

StrReverse(pStr, pStr + len - 1 - steps);

StrReverse(pStr + len - steps, pStr + len - 1);

StrReverse(pStr, pStr + len - 1);

}

int main()

{

char str[] = "abcdef";

RightLoopMove(str, 3);

printf("%s\n", str);

getchar();

return 0;

}

用c语言实现字母移位,【C语言】实现字符串右移位函数_第2张图片

你可能感兴趣的:(用c语言实现字母移位)