版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xckkcxxck/article/details/83012573
题目描述 Description http://codevs.cn/problem/1205/
给出一个英语句子,希望你把句子里的单词顺序都翻转过来
输入描述 Input Description
输入包括一个英语句子。
输出描述 Output Description
按单词的顺序把单词倒序输出
样例输入 Sample Input
I love you
样例输出 Sample Output
you love I
数据范围及提示 Data Size & Hint
简单的字符串操作
解答:这个水题把我卡住了,因为我忘记了c的gets函数和scanf函数对字符串操作该怎么使用了。从别处查到资料:
gets(s)函数与 scanf("%s",&s) 相似,但不完全相同,使用scanf("%s",&s) 函数输入字符串时存在一个问题,就是如果输入了空格会认为字符串结束,空格后的字符将作为下一个输入项处理,但gets()函数将接收输入的整个字符串直到遇到换行为止。
然后我就写出了下面的解法:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int main()
{
int i,n=0;
char a[1000];
char b[100][100];
gets(a);
int j=0,k=0;
for(int i=0; a[i] != '\0'; i++)
{
if(a[i]!=' ')
{
b[j][k]=a[i];
k++;
}else
{
j++;
k=0;
}
}
for(int i=j; i>=0; i--)
cout<<b[i]<<' ';
return 0;
}
然后我看了别人的题解,感觉最简单的就是使用模版来做了:
#include<bits/stdc++.h>
using namespace std;
int main(){
int i=0;
string s[1005];
while(cin>>s[i]){
i++;
}
while(i--){
cout<<s[i]<<' ';
}
return 0;
}
查阅了一下#include<bits/stdc++.h>包含了目前c++所包含的所有头文件。真是神器。
而c++中也有字符串类:标准库类型string表示可变长的字符序列,为了在程序中使用string类型,我们必须包含头文件: #include <string>
如果使用这个就只需要上面的几行代码,实在是很方便!