编写一个函数,将一个字符串中的单词顺序反转。如hello word!变为word! hello
#include <iostream> #include <string.h> using namespace std; void strlcpy(char *s1, const char *s2, int n) { char *s; for(s=s1; 0<n&&*s2!='\0';--n) *s++=*s2++; *s++='\0'; cout<<s1<<endl; } int main() { char *buffer; char str[] ="hello world!"; int len,s,m,n,l=0; len=strlen(str); s=len-1; buffer=(char*) malloc(len+1); while(s>=0){ if(str[s]==' '){ buffer[l++]=str[s--]; }else { n=s; while(s>=0&&str[s]!=' ') s--; m=s+1; while(m<=n){ buffer[l++]=str[m++]; } } } buffer[l]='\0'; strlcpy(str,buffer,len); free(buffer); return 0; }
优化高效版:
#include <iostream> #include <string> #include <cassert> using namespace std; void reverseRange(char* str,int begin,int end) { assert(str != NULL); assert(begin>=0); assert(end<=strlen(str)-1); if(begin>=end) return; while(begin<=end) { char temp = str[begin]; str[begin] = str[end]; str[end] = temp; begin++; end--; } return; } void reverseString(char* str) { assert(str!=NULL); int start=0,end=0,length=strlen(str); reverseRange(str,0,length-1); while(end<length){ if(str[end]!=' '){ start=end; while(end<length&&str[end]!=' ') end++; end--; reverseRange(str,start,end); } end++; } cout<<str<<endl; } int main() { char* p = "hello world!"; char* str = (char*)malloc(sizeof(char)*(strlen(p)+1)); strcpy(str,p); reverseString(str); free(str); return 0; }