实现字符串循环右移n 位与左移n位(建立数组)

编写一个函数,作用是把一个 char 组成的字符串循环

右移 n 个。

比如原来是“abcdefghi”

如果 n=2,,移位后应该是“hiabcdefgh”

左移n个

比如原来是“abcdefghi”

如果 n=2,移位后应该是“cdefghiab”函数头是这样的: //pStr 是指向以’\0’结尾的字符串的指针 //steps 是要求移动的 n void LoopMove ( char * pStr, int steps ) { //…

}

以下是对右移的分析

对于左移其实与右移相同

/**************************************** * File Name : loopMove.c * Creat Data : 2015.3.24 * Author: wk *****************************************/ #include<stdio.h>#include<string.h>#include<stdlib.h>#define MAXLEN 20void LoopMove1(char *str,int n)char *p=str;char temp[MAXLEN];//定义一个数组int len=strlen(str);int remain=len-n;//记录剩余的的字符串长度strcpy(temp,str+remain);strcpy(temp+n,str); /*这是左移需要替换的代码 strcpy(temp,str+n);strcpy(temp+remain,str);*/*(temp+len)='\0';strcpy(p,temp);}void LoopMove2(char *pstr,int n){int remain=strlen(pstr)-n;char temp[MAXLEN];memcpy(temp,pstr+remain,n); memcpy(pstr+n,pstr,remain); memcpy(pstr,temp,n);/* 这是左移需要替换的代码 memcpy(temp,pstr+n,remain);memcpy(pstr+remain,pstr,n);memcpy(pstr,temp,remain);*/}int main(){char pstr[]="abcdef";int n=2;LoopMove1(pstr,n);printf("%s\n",pstr);char pstr2[]="abcdef";LoopMove2(pstr2,n);printf("%s\n",pstr2);system("pause");return 0;}

当眼泪流尽的时候,留下的应该是坚强。

实现字符串循环右移n 位与左移n位(建立数组)

相关文章:

你感兴趣的文章:

标签云: