1.反转字符串
例:hello world 变为 dlrow olleh
程序为:
# include <iostream> using namespace std; # include <stdlib.h> int main() { void reverse(char *s); char a[20]="hello world"; reverse(a); cout<<a<<endl; system("pause"); return 0; } void reverse(char *s) { char *p1=s; char *p2=s+strlen(s)-1; char tmp; while(p1<p2) //交换*p1和*p2的元素 { tmp=*(p1); *p1=*p2; *p2=tmp; p1++; p2--; } }
2.反转每个单词内部的顺序,但单词的顺序不变
如 hello world 变为olleh dlrow 方法是先检测每个单词出现的位置,反转每个单词
程序为:
# include <iostream> using namespace std; # include <stdlib.h> int main() { void reverseword(char *s); char a[20]="hello world"; reverseword(a); cout<<a<<endl; system("pause"); return 0; } void reversespecial(char *s1,char *s2) //反转一个单词 { char *p1=s1; char *p2=s2; char tmp; while(p1<p2) { tmp=*(p1); *p1=*p2; *p2=tmp; p1++; p2--; } } void reverseword(char *s)//颠倒句子中单词 { char *p=s; char *str=0; while(*p!=‘\0‘) { while(*p==‘ ‘&&*p!=‘\0‘) p++; str=p; while(*p!=‘ ‘&&*p!=‘\0‘) p++; reversespecial(str,p-1); } }
3.反转字符串中的单词的顺序,但不反转单词内部的顺序
如hello world变为world hello
程序为:
# include <iostream> using namespace std; # include <stdlib.h> int main() { void reverse(char *s); void reverseword(char *s); char a[20]="hello world"; reverse(a); //cout<<a<<endl; reverseword(a); cout<<a<<endl; system("pause"); return 0; } void reverse(char *s) //反转字符串 { char *p1=s; char *p2=s+strlen(s)-1; char tmp; while(p1<p2) { tmp=*(p1); *p1=*p2; *p2=tmp; p1++; p2--; } } void reversespecial(char *s1,char *s2) //反转子字符串 { char *p1=s1; char *p2=s2; char tmp; while(p1<p2) { tmp=*(p1); *p1=*p2; *p2=tmp; p1++; p2--; } } void reverseword(char *s)//颠倒句子中单词 { char *p=s; char *str=0; while(*p!=‘\0‘) { while(*p==‘ ‘&&*p!=‘\0‘) p++; str=p; while(*p!=‘ ‘&&*p!=‘\0‘) p++; reversespecial(str,p-1); } }
原文:http://blog.csdn.net/u011608357/article/details/23084307