最近看C++课本发现了substr这个神奇的函数,然后就根据这个写了个字符串转置的函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| #include <string> using std::string; string reverse(const string& str) { if (str.length() == 1) return str; if (str.length() == 2) return string(str.substr(1, 1) + str.substr(0, 1)); string sub = str.substr(1, str.length() - 1); return reverse(sub) + str.substr(0, 1); } int main() { string teststr1 = "1"; string teststr2 = "12"; string teststr3 = "123"; string teststr4 = "I love C++."; printf("%s\n", teststr1.c_str()); printf("%s\n", reverse(teststr1).c_str()); printf("%s\n", teststr2.c_str()); printf("%s\n", reverse(teststr2).c_str()); printf("%s\n", teststr3.c_str()); printf("%s\n", reverse(teststr3).c_str()); printf("%s\n", teststr4.c_str()); printf("%s\n", reverse(teststr4).c_str()); }
|
嗯,大概就这样了