题目描述:
给定一个句子(只包含字母和空格), 将句子中的单词位置反转,单词用空格分割, 单词之间只有一个空格,前后没有空格。 比如: (1) “hello xiao mi”-> “mi xiao hello”
输入描述:
输入数据有多组,每组占一行,包含一个句子(句子长度小于1000个字符)
输出描述:
对于每个测试示例,要求输出句子中单词反转后形成的句子
示例一:
输入
hello xiao mi
输出
mi xiao hello
解题思路:
先用getline逐行读取字符串,然后将空格间隔的词按顺序放到栈里,输出的时候从栈顶开始往下输出,需要注意的时string和char数组的转换
代码:
#include <iostream>
#include <string.h>
#include <stack>
using namespace std;
int main() {
string data;
//读取一行字符串
while (getline(cin, data)) {
//将字符串转成char数组
char* store = new char[1000];
int len = data.length();
strncpy(store, data.c_str(), len);
//用栈来存放被空格符分割的词
stack<string> stk;
char* temp = new char[50];
int index = 0;
for (int i = 0; i < len; i++) {
if (data[i] != ' ') {
if (i == len - 1) {
temp[index] = data[i];
temp[index + 1] = '\0';
string num = temp;
stk.push(num);
} else {
temp[index] = data[i];
index++;
}
} else {
temp[index] = '\0';
string num = temp;
stk.push(num);
delete [] temp;
temp = new char[50];
index = 0;
}
}
int count = stk.size();
for (int i = 0; i < count; i++) {
if (i != count - 1) {
cout << stk.top() << ' ';
stk.pop();
} else {
cout << stk.top() << endl;
stk.pop();
}
}
}
}