#include<stdio.h>
#include <string.h>
int main(){
char s[100]="";
gets(s);
if(strchr(s,' ')==NULL){
printf(s);
}else{
while(strchr(s,' ')!=NULL){
printf("%s ", strrchr(s,' ')+1);//加1操作主意是试指针后移一位(char字符的长度!!!char字符的长度为1)
*strrchr(s,' ')=0;
}
printf("%s",s);
}
return 0;
}
C++版本:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main(){
string s;
stack<string>st;
while(cin>>s){
st.push(s);
}
cout << st.top();
st.pop();
while(!st.empty()){
cout<<' '<<st.top();
st.pop();
}
return 0;
}
总结:
1、利用#include <string.h>
头文件的两个函数使得对于字符串的查找和打印方便了很多。
2、注意strchar()函数和strrchar()的区别:
①char *strchr(const char *s, int c)
功能: 查找字符串s中首次出现c字符的位置
说明: 返回首次出现c的位置的指针,返回的地址是被查找的字符串指针开始的第一个与c相同字符的指针,若s中不存在c则返回NULL。。。。
返回值: 成功返回要查找的字符第一次出现的位置,否则返回NULL。
②char *strrchr(const char *s, int c)
功能: 查找一个字符c在一个字符串s中最后一次出现的位置(也就是从s的右侧开始查找字符c首次出现的位置),并返回从字符串中的字符c所在的位置开始直到字符串s结束的所有字符。 若没有找到字符c,则返回NULL。
3、c++实现用了栈先进先出的特点,更加便捷。