c++如何使用递归删除字符串中的某字符?

大一c++课后习题:
c++如何使用递归删除字符串中的某字符?

基于Monster 组和GPT的调写:

用递归来删除一个字符串中的某个字符。以下是一个递归函数的示例,该函数删除字符串中的所有给定字符:

#include <iostream>
#include <string>

using namespace std;

string removeChar(string s, char c)
{
    if (s.length() == 0) {
        return s;
    }
    else {
        if (s[0] == c) {
            return removeChar(s.substr(1), c);
        }
        else {
            return s[0] + removeChar(s.substr(1), c);
        }
    }
}

int main()
{
    string s = "Hello World";
    char c = 'l';
    s = removeChar(s, c);
    cout << s << endl;
    return 0;
}