因此,该函数应该返回字符串中的所有大写字母,但如果它是大写字母,则仅返回第一个字母。因此,我认为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;
}
您不能使用您的函数,因为在每个新调用中,您都定义了一个新字符串。
下面的函数根据需要运行。
#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;
}