句子反转

题目描述:

给定一个句子(只包含字母和空格), 将句子中的单词位置反转,单词用空格分割, 单词之间只有一个空格,前后没有空格。 比如: (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();
			}
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值