Home > Back-end >  Can I use str.append to create a new string with no vowels?
Can I use str.append to create a new string with no vowels?

Time:11-12

I'm doing a practice assignment from codewars.com to create a program that will take a troll's comments and transform it into a statement with no vowels.

My idea is to get the comment, return all the characters that are not vowels and put it in a new string array using an iterator.

int main()
{
    string troll;
    string disemvoweled;
    
    getline(cin,troll);
    int length= (int) troll.length();
    
    string::iterator it;
    
    for (it = troll.begin();it!=troll.end();it  ) {
        if (*it!='a' || *it!='e' || *it!='i' || *it!='o' || *it!='u' || *it!='A' || *it!='E' ||*it!='I' || *it!='O' || *it!='U'){
            disemvoweled.append(*it);
        }
    }
    cout << disemvoweled;

    return 0;
}

I get an error:

no matching function for call to std::__cxx11::basic_string<char>::append(char&)'

My first question is why is the append() not working?

My second question is, without providing any solution, which concept of C can help me improve this code? I was thinking perhaps using a container of some sort and popping out a vowel?

CodePudding user response:

why is the append() not working?

The overloads for append can be found here and as you can see they expect argument of different types(like const std::string& and const char*) while you're providing the char type argument.

You can solve this by using = as follows:

disemvoweled = (*it);

which concept of C can help me improve this code?

You can improve the code by using std::set as follows:

getline(cin,troll);
std::set<char> vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E','I','O','U'};

for (auto it = troll.begin();it!=troll.end();it  ) {
    if (vowels.find(*it) == vowels.end())
    {
        disemvoweled = (*it); //can also use disemvoweled.append(1, *it);
    }
}
cout << disemvoweled;

CodePudding user response:

You can use range-v3:

#include <string>
#include <iostream>

#include <range/v3/all.hpp>

constexpr bool is_not_vowel(char const ch) noexcept {
    switch (ch) {
        case 'a': case 'e': case 'i': case 'o': case 'u': 
        case 'A': case 'E': case 'I': case 'O': case 'U':
            return false;
        default:
            return true;
    }
}

int main() {
    std::string str = "hello world";
    std::string no_vowels;
    ranges::copy(
        str | ranges::views::filter(is_not_vowel),
        std::back_inserter(no_vowels)
    );

    std::cout << no_vowels << '\n';
}

See online

  • Related