简答题
偏难
#13177
倒排文字 题目描述 给定若干单词,请你将输入的所有单词的顺序倒排并输出,单词之间用单个空格分隔。 输入格式 输入共一行,一个字符串。 输出格式 输出为按要求排序…
倒排文字
题目描述
给定若干单词,请你将输入的所有单词的顺序倒排并输出,单词之间用单个空格分隔。
输入格式
输入共一行,一个字符串。
输出格式
输出为按要求排序后的字符串。
输入样例
I am a student
输出样例
student a am I
说明提示
字符串长度不超过100
保证单词都由可见字符组成,且单词之前有且仅有一个空格。
答案与解析
正确答案:<pre class="brush:cpp;toolbar:false">//C++参考代码1
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
string input;
getline(cin, input); // 读取整行输入
vector<string> words; // 用来存储单词
string word;
// 分割字符串为单词
for (char c : input) {
if (c == ' ') {
if (!word.empty()) {
words.push_back(word);
word = "";
}
} else {
word += c;
}
}
if (!word.empty()) {
words.push_back(word);
}
// 倒序输出单词
for (int i = words.size() - 1; i >= 0; i--) {
cout << words[i];
if (i > 0) {
cout << " ";
}
}
return 0;
}</pre><pre class="brush:cpp;toolbar:false">//C++参考代码2
#include<bits/stdc++.h>
using namespace std;
string a,x[101];
int main(){
int t=1;
getline(cin,a);
for(int i=0;i<a.size();i++){
if(a[i]!=' '){
x[t]+=a[i];
}
else{
t++;
}
}
for(int i=t;i>0;i--){
if(x[i]!="")
cout<<x[i]<<' ';
}
return 0;
}</pre><pre class="brush:cpp;toolbar:false">//C语言代码
#include<stdio.h>
#include<string.h>
int main()
{
char a[101]={0};
int i,j,len,t;
gets(a);
len=strlen(a);
t=len;
for(i=len-1;i>=0;i--) //从字符串的最后进行遍历
{
if(a[i]==' ') //当遇到的字符为空格时,说明此时已找到了一个完整的单词,位置是i~t-1
{
for(j=i+1;j<=t-1;j++) //从空格的后面一个字符打印到第t-1个字符
{
printf("%c",a[j]);
}
printf(" "); //打印空格
t=i; //a[i]字符为空格,把第i个位置赋值给t,以后的打印到t-1为止
}
}
for(j=0;j<t;j++)
{
printf("%c",a[j]);
}
return 0;
}</pre>
这道题暂未补解析。