字符串的循环移动
?
部分來自<<程序員面試寶典>>
#include<stdio.h> #include<string.h>//字符串循環右移 void strMove1(char *pStr,int steps) {int n=strlen(pStr)-steps;char tmp[20];strcpy(tmp,pStr+n);//先保存要調頭的字符,因為下面前移的時候可能被覆蓋//printf("%s\n",tmp);strcpy(tmp+stpes,pStr);//賦值剩下的字符串,對tmp前移了,前移的空位來保存被調頭的字符//printf("%s\n",tmp);*(tmp+strlen(pStr))='\0';//用'\0'截斷strcpy(pStr,tmp);printf("%s\n",pStr); }//字符串循環的右移 void strMove2(char *pStr,int steps) {int n=strlen(pStr)-stpes;char tmp[20];memcpy(tmp,pStr+n,steps);//先初始化tmp為要調頭的字符memcpy(pStr+steps,pStr,n);//對要掉頭后面位置指定初始化字符memcpy(pStr,tmp,steps);//補前面的printf("%s\n",pStr); }//字符串奇數位的右移 void strMove3(char *pStr) {int i,n,k;char c;n=0;for(i=0;pStr[i]!='\0';i++)n++;if(0==n%2)k=n-1;elsek=n-2;c=pStr[k];//保存第一個奇數for(i=k-2;i>=1;i=i-2)//奇數位的前移2位pStr[i+2]=pStr[i];pStr[1]=c;//歸位 }int main() {int n=2;char str1[20]="abcde";strMove1(str1,n);char str2[20]="abcde";strMove2(str2,n);char str3[20]="abcdefg";strMove3(str3);printf("%s\n",str3);return 0; }?
打印:deabc
? ? ? ? ? ? deabc
? ? ? ? ? ? afcbedg
再看一個函數:
memset(s,ch,n):將s所指向的某一塊內存中的前n個字節的內容全部設置為ch指定的ASCII值,這個函數通常為新申請的內存做初始化工作
?
再看一個數組的移動:
?
#define N 10 #include<iostream> using namespace std;//數組的循環移動 void arrMove(int w[],int p,int n)//p為要循環移動的位數 {int x,j,tmp;for(x=0;x<=p;x++)//每一次外圍的for循環,都會使這個數組移動一次,且調用的數完成歸位{tmp=w[0];//每次都歸位了,w[0]也是不斷在變化for(j=1;j<n;j++)w[j-1]=w[j];w[n-1]=pos;} }int main() {int a[N]={1,2,3,4,5,6,7,8,9,10};int i,n=10;arrMove(a,5,n);for(i=0;i<N;i++)cout<<a[i]<<endl;retrun 0; }打印:7
?
? ? ? ? ?8
? ? ? ? ?9
? ? ? ? ?10
? ? ? ? ?1
? ? ? ? ?2
? ? ? ? ?3
? ? ? ? ?4
? ? ? ? ?5
? ? ? ? ?6
?
循環移動:用字符串相關函數拼接字符,都是先保存要循環調頭移動的字符,再進行拼接或移動,再完成歸位操作。
?
?
?
總結