字符串右旋
题目描述:
请实现字符串右循环移位函数,比如:“abcdefghi” 循环右移2位就是“hiabcdefg”
函数原型:
void RightLoopMove(char *pstr,unsigned short steps)
函数参数说明:
pstr: Point to a ‘\0’ terminated string
steps: The rotate shift numbers
方法一:
利用临时数组存放旋转后的字符串,并将其输出,实现过程如下图
具体代码:
void RightLoopMove(char *pstr, unsigned short steps)
{
char *p = pstr;
char *q = pstr;
char temp[20];
int i = 0;
while (*p != '\0')
{
p++;
}
p -= steps;
while (steps)
{
temp[i] = *p;
i++;
p++;
--steps;
}
p = p- (steps+2);
while (*q != *p)
{
temp[i] = *q;
q++;
i++;
}
temp[i] = '\0';
printf("%s\n", temp);
}
方法二:
右旋字符串 n 位可转化为左旋字符串 len-n 位
(len 为字符串长度)
代码:
//右旋n位就等于左旋len-n位
void RightLoopMove(char *pstr, unsigned short steps)
{
char *start = pstr;
char *end = pstr;
while (*end != '\0')
{
end++;
}
//字符串的长度
int len = end - pstr;
int count = len - steps;
while (count)
{
*end = *start;
end++;
start++;
count--;
}
printf("%s \n", start);
}
方法三:
构建双倍字符串,输出你所需要的字符串
代码:
//构建双倍字符串,找出所需字符串
void RightLoopMove(char *pstr, unsigned short steps)
{
char* start = pstr;
char* end = pstr;
while (*end != '\0')
{
end++;
}
//字符串长度
int len = end - pstr;
strncpy(end, pstr,len);
//*end = '\0';
end = end - steps;
while (len)
{
printf("%c ", *end);
end++;
len--;
}
}