您的位置:首页 > 其它

编写一个函数,把一个char组成的字符串循环右移n位

2015-08-28 14:53 183 查看
例如:把一个char 组成的字符串循环右移 n 位,原来是 ”abcdefghi“,如果 n = 2,移位后应该是 ”hiabcdefgh“

函数头如下:

/**

@ pstr 指的是以 '\0' 结尾的字符串指针

@ steps 指的是要求移动的位数 n

*/

void LoopMove(char *str, int steps)

{

........

}

void LoopMove(char *pStr, int steps)
{
	if (pStr==NULL)
		return ;
	int len = strlen(pStr);
	steps = steps % len;

	int lenNew = len-steps; //移动后的后lenNew位字符
	char *strTemp = (char *)malloc(lenNew+1);
	//将移位前的前lenNew为保存起来
	if (strTemp==NULL) {
		puts("申请内存失败!");
		return ;
	}
	strncpy(strTemp, pStr, lenNew);
	strTemp[lenNew] = '\0';

	//将需要移动的后steps位字符保存到pstr前 steps位
	int i = 0;
	for (; i<steps; ++i)
	{
		pStr[i] = pStr[lenNew++];
	}
	pStr[i] = '\0';
	strcat(pStr, strTemp); //字符串连接起来

}

#define MAX_LEN 20
void Loop1(char *pstr, int steps)
{
	char temp[MAX_LEN];
	int n = strlen(pstr)-steps;
	strcpy(temp, pstr+n);
	strcpy(temp+steps, pstr);
	*(temp+strlen(pstr)) = '\0';
	strcpy(pstr,temp);
}

void Loopmem(char *pstr, int steps)
{
	char temp[MAX_LEN];
	int n = strlen(pstr) - steps;
	memcpy(temp, pstr+n, steps);
	memcpy(temp+steps, pstr, n);
	memcpy(pstr,temp,strlen(pstr));

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: