1009 說反話 (20分)
題目地址:https://pintia.cn/problem-sets/994805260223102976/problems/994805314941992960
給定一句英語,要求你撰寫程式,將句中所有單詞的順序顛倒輸出,
輸入格式:
測驗輸入包含一個測驗用例,在一行內給出總長度不超過 80 的字串,字串由若干單詞和若干空格組成,其中單詞是由英文字母(大小寫有區分)組成的字串,單詞之間用 1 個空格分開,輸入保證句子末尾沒有多余的空格,
輸出格式:
每個測驗用例的輸出占一行,輸出倒序后的句子,
輸入樣例
Hello World Here I Come
輸出樣例
Come I Here World Hello
我的理解
從后往前,每遇到一個空格,輸出這個空格之后的一個單詞,然后更改單詞尾的位置,在遍歷一遍之后,因為第一個單詞之前沒有空格,所以剩余第一個單詞未輸出,輸出第一個單詞即可,
代碼段
#include<iostream>
//#include<string>
#include<string.h>
using namespace std;
int main() {
// #include<string> 中的函式
// string words;
// getline(cin, words);
char words[80];
// #include<string.h> 中的函式
// 第二位引數代表允許輸入的字符個數,小于,不會等于 ,例如81 只能輸入80個字符
cin.getline(words, 81);
int length = strlen(words);
int indexA = length - 1;
int indexZ = length;
for ( ; indexA >= 0; indexA--) {
if (words[indexA] == ' ') {
for (int index = indexA + 1; index < indexZ; index++) {
cout << words[index];
}
cout << ' ';
indexZ = indexA;
}
}
// 回圈結束后,indexA 等于 -1;
// 剩余第一個單詞未輸出
for (indexA++; indexA < indexZ; indexA++) {
cout << words[indexA];
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/110937.html
標籤:其他
上一篇:BigInteger和BigDecimal的基本用法
下一篇:求n!末尾0的個數
