【C++】 --翻转字符串的两种方法

题目描述

将一句话的单词进行倒置,标点不倒置。比如 I like beijing. 经过函数后变为:beijing. like I

输入描述:

每个测试输入包含1个测试用例: I like beijing. 输入用例长度不超过100

输出描述:

依次输出倒置之后的字符串,以空格分割

示例1

输入: I like beijing.
输出: beijing. like I

思路1:先通过substr将字符串分割成一个一个的单词放入vector中,再将vector中的单词逆序输出,即可完成倒置字符串
代码:

#include <iostream>
#include <stdlib.h>
#include <string>
#include <vector>
using namespace std;
int main()
{
	
	while (1)
	{
		string str;
		getline(cin, str);
		vector<string> v;
		int pos = 0, start = 0;
		while(pos<str.size())
		{
			pos = str.find(' ', start);
			string ret = str.substr(start, pos - start);
			v.push_back(ret);
			start = pos + 1;
		}
		
		vector<string>::reverse_iterator it = v.rbegin();
		while (it != v.rend())
		{
			cout << *it << " ";
			it++;
		}
		cout << endl;
	}
	system("pause");
	return 0;
}

思路2:先完成整个字符串的翻转,再完成局部的翻转,即就是找到空格后停下,完成翻转。
代码:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
	string s;
	 注意这里要使用getline,cin>>s遇到空格就接收结束了
	getline(cin, s);
	 翻转整个句子 
	reverse(s.begin(), s.end()); // 翻转单词
	auto start = s.begin();
	while (start != s.end())
	{
		auto end = start;
		while (end != s.end() && *end != ' ')
			end++;
		reverse(start, end);
		if (end != s.end())
			start = end + 1;
		else
			start = end;
	}
	cout << s << endl;
	system("pause");
	return 0;
}
发布了33 篇原创文章 · 获赞 13 · 访问量 1046

猜你喜欢

转载自blog.csdn.net/Vicky_Cr/article/details/104852198