實現字串中各單詞翻轉
阿新 • • 發佈:2019-01-04
程式碼一:
1、將字串中的所有單詞翻轉,例如:src中的字串為“I am from Beijing”,翻轉後為 "I ma morf gnijieB"
程式碼二:
1 先進行全域性翻轉 例如:“I am from Beijing” -> " gniieB morf ma I"
2 再將各個單詞進行翻轉 “Beijing from am I”
1、將字串中的所有單詞翻轉,例如:src中的字串為“I am from Beijing”,翻轉後為 "I ma morf gnijieB"
2、再進行全域性翻轉"Beijing from am I"
#include <iostream>
using namespace std;
void RevStr( char *src) { if (src==NULL) return ; //1 將str中的各個單詞進行翻轉 char *start;//單詞的開頭 char *end;//單詞的末尾 char *ptr;//用於遍歷整個字串 start=end=ptr=src; while(*ptr++!='\0')//遍歷字元創 { if(*ptr==' '||*ptr=='\0')//找到一個單詞 { end=ptr-1;//end指向單詞末尾 while(start<end) swap(*start++,*end--);//把單詞的字母逆置 start=end=ptr+1;//指向下一個單詞開頭 } } //2 進行全域性翻轉 start=src;//start指向字串開頭 end=ptr-2;//end指向字串末尾 while(start<end) { swap(*start++,*end--);//把整個字串逆置 } }
程式碼二:
1 先進行全域性翻轉 例如:“I am from Beijing” -> " gniieB morf ma I"
2 再將各個單詞進行翻轉 “Beijing from am I”
void RevStr(char *src) { if (src==NULL) return ; char *start=src; char *end=src; char *ptr=src; //進行全域性翻轉 while(*ptr++!='\0'); end=ptr-2;//end指向字串的末尾 while(start<end) { swap(*start++,*end--); } //2 區域性每個單詞進行翻轉 start=src; end=ptr-2; ptr=start; while(*ptr++!='\0') { if(*ptr==' '||*ptr=='\0') { end=ptr-1; while(start<end) { swap(*start++,*end--); } start=end=ptr+1; } } }
int main()
{
char src[]="I am from Beijing";
cout<<"src: "<<src<<endl;
RevStr(src);
cout<<"des: "<<src<<endl;
return 0;
}