示例: 使用递归反转句子。
#include <iostream> using namespace std; // function prototype void reverse(const string& a); int main() { string str; cout << " Please enter a string " << endl; getline(cin, str); // function call reverse(str); return 0; } // function definition void reverse(const string& str) { // store the size of the string size_t numOfChars = str.size(); if(numOfChars == 1) { cout << str << endl; } else { cout << str[numOfChars-1]; // function recursion reverse(str.substr(0, numOfChars-1)); } }
输出
Enter a sentence: margorp emosewa awesome program
在这个程序中,用户被要求输入一个存储在字符串对象
str中的字符串。
然后,调用
reverse()
函数,这是一个递归函数。
在这个函数中,我们将输入字符串的大小存储在
numOfChars 变量中。
在第一个函数调用中,
reverse()
打印带有代码的字符串的最后一个字符:
cout << str[numOfChars-1];
请记住,字符串实际上是字符数组,因此字符串的每个单独字符都可以表示为字符串数组
str[] 的索引。
在下一行,递归函数被调用:
reverse(str.substr(0, numOfChars-1));
这里,
substr()
给出字符串直到最后一个字符,它再次传递给
reverse()
函数。
在下一个
reverse()
调用中,打印倒数第二个字符,因为字符串比最后一个字符少一个。在此之后,最后一个字符再次从字符串中截取并传递给
reverse()
函数。
直到字符串的长度等于 1,当最后一个字符(或第一个字符)被打印并且循环结束时。