3.6每日一题

3.6 每日一题

给定字符串,倒序输出

例如:输入:I like beijing.
   输出:beijing. like I
   思路:以空格为标志,遍历字符串,遇到空格就将前面的字母存放在一个vector数组内,即为一个单词,然后以单词为单位倒序输出
   代码实现:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

std::vector<std::string>& ReverseWord(std::string str, std::vector<std::string>& result) {
	
	std::string current_word;
	for (int i = 0; i < str.size(); i++) {
		if (str[i] == ' ') {
			result.push_back(current_word);
			current_word = "";
		}
		else {
			current_word += str[i];
		}
	}
	if (current_word.size() != 0) {
		result.push_back(current_word);
	}
	return result;
}
int main()
{
	string str; //hello world

	getline(cin, str);
	std::vector<std::string> result;
	ReverseWord(str, result);
	for (int i = result.size()-1; i >= 0; --i) {
		if (i == 0) {
			std::cout << result[i];
		}
		else {
			std::cout << result[i] << " ";
		}

	}
	return 0;
}

运行结果
在这里插入图片描述
参考答案
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/lxb18821659801/article/details/88308830