The string is in reverse order at the specified position

/* 
   给定一个字符串str,和一个整数i,i代表str中的位置,
   将str[0..i]移到右侧,str[i+1..N-1]移动到左侧
   思路:先部分逆序,再整体逆序
*/
#include <iostream>
#include <string>
using namespace std;

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

void reversalStrOrderIndex(string& str, int index) {
    
    
	if (str.empty() || index < 0 || index >= str.length()) {
    
    
		return;
	}
	reversal(str, 0, index);
	reversal(str, index + 1, str.length() - 1);
	reversal(str, 0, str.length() - 1);
}

int main() {
    
    
	string str("hello");
	cout << str << endl;
	reversalStrOrderIndex(str, 1);
	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/105340898