如何使此递归函数从字符串中提取大写字母?

问题描述 投票:0回答:1

因此,该函数应该返回字符串中的所有大写字母,但如果它是大写字母,则仅返回第一个字母。因此,我认为i + 1无法正常工作。而且,我必须对此代码使用递归。我不允许使用isupper()或任何其他“快捷方式”。有人看到代码中出了什么问题吗?

string Return_Caps(const string& s, int pos = 0){
    string temp;
    string a;
    if(s[pos] < 'A' && s[pos] > 'Z'){ // if the position does not have any capital letters, return a
        return a;
    }
    else{
        if(s[pos] >= 'A' && s[pos] <= 'Z'){ 
            temp = temp + s[pos];
            Return_Caps(s, pos + 1);
        }
    }
    return temp; 
}



c++ function recursion uppercase
1个回答
0
投票

您不能使用您的函数,因为在每个新调用中,您都定义了一个新字符串。

下面的函数根据需要运行。

#include<string>
#include<iostream>

std::string Return_Caps(const std::string& s, size_t pos=0){

    if( s.size()== pos) return "";//base case
    if(s[pos] >= 'A' && s[pos] <= 'Z') return s[pos]+Return_Caps(s, pos+1);//capital found
    else return ""+Return_Caps(s, pos+1);//non capital lette

}

//To test
int main(){

    std::string s {"W0oe3fQWEkjkUYUnnQ"};

    std::string capitals = Return_Caps(s, 0);

    std::cout<<capitals;
}
© www.soinside.com 2019 - 2024. All rights reserved.