小技巧----“三步翻转法”

例:实现字符串左移函数,比如"abcdefghi"循环左移3位就是”defghiabc".




#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>

void revers(char *left,char *right)                      //翻转函数,left代表起始位置,right代表结束位置
{
	assert(left);
	assert(right);
	char tmp = 0;
	while (left < right)
	{
		tmp = *left;
		*left = *right;
		*right = tmp;
		left++;
		right--;
	}
}
void leftLoopMove(char *pStr, unsigned short steps)
{
	assert(pStr);
	int len = strlen(pStr);                   
	steps = steps%len;                                    //这样可以处理steps不合法的情况
	revers(pStr,pStr+steps-1);                            //首先翻转前steps个字符
	revers(pStr + steps, pStr + len - 1);                 //再翻转剩下的字符
	revers(pStr, pStr + len - 1);                         //再将整体翻转
} 
int main()
{
	char arr[50] = { 0 };
	unsigned short steps = 0;               //要右移的个数
	scanf("%s%hd",arr,&steps);
	leftLoopMove(arr,steps);
	printf("%s\n", arr);
	system("pause");
	return 0;
}


你可能感兴趣的:(小技巧----三步翻转法)