English 中文(简体)
使用 c++ 中的递转从字符串中删除所有对应音
原标题:Deleting all consonants from a string using recursion in c++

我对编程几乎是全新的,我尝试学习C++。这是我第一次感到自己撞墙。我试图搜索,但因为人们通常使用环路解决我找不到的问题。

我试图找到一个循环解决方案, 从字符串中删除所有同义词(我想我知道如何使用循环解决它,

#include <iostream>
#include <string>

using namespace std;

int i = 0;
string s("");

string del_cons(string z){
    if(i == (z.length()-1) ){
        s+= z.substr(i);
        return s;
    }
    else if(z[i] ==  a  || z[i] ==  e  || z[i] ==  i  || z[i] ==  o  || z[i] ==  u ){
        i++;
        s+= del_cons(z.substr(i));
        return s;
    }
    else{
        s+= z.substr(i,1); 
        i++;
        s+= del_cons(z.substr(i));
        return s;
    }
}


int main(){
    string x;
    getline(cin, x);

    cout << del_cons(x) << endl;

    return 0;
}

代码编译, 但是当用字符串尝试它时, 我得到这个错误信息 :

terminate called after throwing an instance of  std::out_of_range 
what():  basic_string::substr: __pos (which is 3) > this->size() (which is 2)

(Speicherabzug geschrieben)

在玩游戏代码时,这条线似乎是问题所在:

s+= del_cons(z.substr(i));

有人能给我一个提示吗?我做错了什么?我似乎在误用 substr () 函数, 但我不知道怎么用。非常感谢。

最佳回答

If you just wanna learn about recursion and do more by hand , it is probably easier to look if there are still consonants existing in the string, possibly using z.find_first_of(consonants), where consonants might be a string consisting of all the consonants. If it returns std::string::npos, no consonant was found and you can return the input string (stop criterion). Otherwise you take the consonant out (you now know its position), maybe using z.substr and concatenating the substrings before and after the consonant. Then you call your function recursively with the new string.

然后您可以写入一个更一般的函数, 需要第二个字符串, 包含您想要从字符串中删除的所有字符 。

此外,使用全球变量作为递归参数(例如,在函数中有两个递归电话时,您要做什么?) 也不应该在函数完成时重置这些功能,或者要多次调用这些功能。在您的情况下,您用从一开始就必须处理的字符串调用函数,但 i 可能已经增加。您宁愿将 code>作为一个参数来表示要开始的字母,或者更确切地说,改变您函数的结构。当我以递归方式写函数时,我常常首先想到停止条件:在哪些情况下没有做任何事情(如空字符串或没有配音的字符串)?然后我想其他情况下应该做什么事情。

使用 C++20 s erase_if() 的非常简单、非正统的解决方案可以看起来像以下。 您可能不会学到关于循环的任何东西, 但是当您使用 STL 算法来表达某些东西时, 这样做是良好做法。 它使用小的、 可重复使用的函数 。 replace_if 也可以返回 retell , 确定是否清除元素。 我通过 is_ concontonant 函数来消除元素, 这样它就能消除所有拼写。 您可以轻松创建一个功能, 抹掉所有元, 函数 会被传送到 inerase_if

#include <string>
#include <cctype>
#include <algorithm>

auto contains(char c, const std::string& s) -> bool {
    return std::find(s.cbegin(), s.cend(), c) != s.cend();
}

auto is_vowel(char c) -> bool {
    static const std::string vowels("aeiou");
    return (std::isalpha(c) && contains(std::tolower(c), vowels));
}

auto is_consonant(char c) -> bool{
    return (std::isalpha(c) && !is_vowel(c));
}

auto remove_consonants(std::string s) -> std::string {
    std::erase_if(s, is_consonant);
    return s;
}

int main() {
    const std::string str("My string, of which I want to remove ALL consonants.");
    const auto str_without_consonants = remove_consonants(str);
}
问题回答

也忍无可忍

#include <iostream>
#include <string>
#include <cctype>

using namespace std::literals::string_literals;

std::string del_cons(std::string const & str)
{
    if (!str.size())
        return "";

    if (!std::isalpha(static_cast<unsigned char>(str[0])) ||
        "AEIOUaeiou"s.find(str[0]) != str.npos )
        return str.substr(0, 1) + del_cons(str.substr(1));

    return del_cons(str.substr(1));
}

int main()
{
    std::string input;
    std::getline(std::cin, input);
    std::cout << del_cons(input) <<  
 ;
}

对不起,我忍不住...

#include <string>
#include <iostream>
#include <algorithm>

int main()
{
    std::string s;
    std::getline( std::cin, s );
    s.erase(
        std::remove_if(
            s.begin(),
            s.end(),
            [](unsigned char x){
                return std::string( "aeiouAEIOU" ).find( x ) == std::string::npos;
            }
        ),
        s.end()
    );
    std::cout << s << std::endl;
}




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?