20.C++递归实现反转字符串

#include 
#include  
using namespace std;
string reverse(string& str) {
	if (str.length() > 1) {
		string sub = str.substr(1, str.length() - 2);
		//string s1 = str.substr(str.length() - 1, 1);
		//string s2 = str.substr(0, 1);
		return str.substr(str.length() - 1, 1) + reverse(sub) + str.substr(0, 1);
	}
	else {
		return str;
	}

}
int main() {
	string str;
	cout << "输入一个字符串:";
	cin >> str;
	cout << "原字符串为:" << str << endl;
	cout << "倒序反转后为:" << reverse(str) << endl;
	return 0;
}
#include 
#include  
using namespace std;
string reverse(string& str) {
	if (str.length() > 1) {
		string sub = str.substr(1, str.length() - 2);//截掉头和尾巴
		string s1 = str.substr(str.length() - 1, 1);//拿到尾巴
		string s2 = str.substr(0, 1);//拿到头
		string s3 = s1 + reverse(sub) + s2;//当前得到的数据
		return s3;
	}
	else {
		return str;
	}

}
int main() {
	string str;
	cout << "输入一个字符串:";
	cin >> str;
	cout << "原字符串为:" << str << endl;
	cout << "倒序反转后为:" << reverse(str) << endl;
	return 0;
}

20.C++递归实现反转字符串_第1张图片

你可能感兴趣的:(C++,字符串,c++)