Reverse word order of string

/*  
    实现字符串的按词倒序功能(注意不是完全倒序),
    如果函数输入为字符串“Nothing Is Impossible”,则输出为字符串“Impossible Is Nothing”

    思路一: 先将整个字符串翻转,然后逐个单词翻转
    思路二: 先逐个单词翻转,然后翻转整个字符串
*/

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

void reversal(string& str, int strL, int strR) {
    
    
	if (str.empty() || strL < 0 || strR < 0 || strR <= strL) {
    
    
		return;
	}
	while (strL < strR) {
    
    
		char tmp = str.at(strL);
		str.at(strL++) = str.at(strR);
		str.at(strR--) = tmp;
	}
}

void reversalStrOrderWorld(string& str) {
    
    
	if (str.empty()) {
    
    
		return;
	}
	vector<int> index;
	for (int i = 0; i < str.length(); i++) {
    
    
		if (str.at(i) == ' ') {
    
    
			index.push_back(i);
		}
	}
	index.push_back(str.length());
	int strL = 0;
	int strR = 0;
	/* 逐词翻转 */
	for (int e : index) {
    
    
		strR = e;
		reversal(str, strL, strR - 1);
		strL = strR + 1;
	}
	/* 整体翻转 */
	reversal(str, 0, str.length() - 1);
}

int main() {
    
    
	string str{
    
     "Nothing Is Impossible" };
	cout << str << endl;
	reversalStrOrderWorld(str);
	cout << str << endl;
	system("pause");
	return 0;
}

If there is any infringement, please contact to delete it. If there is an error, please correct me, thank you

Guess you like

Origin blog.csdn.net/xiao_ma_nong_last/article/details/105279733