How to remove consonants from a string? [closed]

天大地大妈咪最大 提交于 2019-12-13 10:54:43

问题


Here is my code:

#include <iostream>
#include <string>
#include<bits/stdc++.h>
using namespace std;

int main() 
{
    int n;
    cin >> n;

    while(n--)
    {
        string str;
        char a[] = {'a','e','i','o','u','A','E','I','O','U'};
        getline(cin, str);

        for(int i=0 ;i<str.length(); i++)
        {
            for(int j=0; j<10; j++)
            {
                if(str[i]==a[j])
                {
                    cout << str[i];
                }
            }
        }
        cout << "\n"; 
    }
    return 0;
}

Test cases are :

HmlMqPhBfaVokhR 
wdTSFuI 
IvfHOSNv 

I am not removing anything but I am printing only vowels. But, some test cases didn't pass. Maybe this code doesn't work on multiple test cases.


回答1:


Try this for proper console in :

int main()
{
    int n;
    std::cin >> n;
    std::cin.ignore();   // fix
    /* remaining code */
    return 0;
}

> To find the vowels in a string

On way of finding the vowels in a string is using a std::binary_search each character of the given string in a vowel table.

  1. Make a sorted array of char s of all vowels(i.e. vowels array).
  2. For each char of the input string, std::binary_search in the vowels array.
  3. If std::binary_search returns true(meaning the char is an vowel), print the char of the string.

Following is the example code! (See live online)

#include <iostream>
#include <string>
#include <algorithm> // std::for_each, std::binary_search, std::sort
#include <array>     // std::array

int main()
{
    std::array<char, 10> a{ 'a','e','i','o','u','A','E','I','O','U' };
    std::sort(a.begin(), a.end()); // need sorted array for std::binary_search

    const std::string str{ "HmlMqPhBfaVokhR wdTSFuI IvfHOSNv" };
    std::for_each(str.cbegin(), str.cend(), [&](const char str_char)
    {
        if (std::binary_search(a.cbegin(), a.cend(), str_char))
            std::cout << str_char << " ";
    });
    return 0;
}

Output:

a o u I I O

> To remove the vowels from a string

Use erase-remove idiom as follows(till c++17).

  1. Make a sorted array of char s of all vowels(i.e. vowels array).
  2. Using std::remove_if, collect the iterators pointing to the characters, which are vowels. A lambda function can be used as the predicate for std::remove_if, where the std::binary_search is used to check the char in the string exists in the vowels array.
  3. Using std::string::erase, erase all the collected characters(i.e. vowels) from the string.

Following is an example code! (See live online)

#include <iostream>
#include <string>
#include <algorithm> // std::sort, std::binary_search, std::remove_if
#include <array>     // std::array

int main()
{
    std::array<char, 10> a{ 'a','e','i','o','u','A','E','I','O','U' };
    std::sort(a.begin(), a.end()); // need sorted array for std::binary_search

    std::string str{ "Hello World" };
    // lambda(predicate) to check the `char` in the string exist in vowels array
    const auto predicate = [&a](const char str_char) -> bool { 
        return std::binary_search(a.cbegin(), a.cend(), str_char);
    };
    // collect the vowels
    const auto vowelsToRemove = std::remove_if(str.begin(), str.end(), predicate);
    // erase the collected vowels using std::string::erase
    str.erase(vowelsToRemove, str.end());

    std::cout << str << "\n";
    return 0;
}

Output:

Hll Wrld

Since c++20, one can use std::erase_if for this, which would be less error prone than the the above one. (See online live using GCC 9.2)

#include <iostream>
#include <string>    // std::string, std::erase_if
#include <array>     // std::array

int main()
{
    std::array<char, 10> a{ 'a','e','i','o','u','A','E','I','O','U' };
    std::sort(a.begin(), a.end()); // need sorted array for std::binary_search

    std::string str{ "Hello World" };
    // lambda(predicate) to check the `char` in the string exist in vowels array
    const auto predicate = [&a](const char str_char) -> bool { 
        return std::binary_search(a.cbegin(), a.cend(), str_char);
    };

    std::erase_if(str, predicate); // simply erase

    std::cout << str << "\n";
    return 0;
}

> To remove the consonants from a string

To remove the consonants from the given string, in the above predicate negate the result of std::binary_search. (See live online)

const auto predicate = [&a](const char str_char) -> bool { 
    return !std::binary_search(a.cbegin(), a.cend(), str_char);
    //     ^^ --> negate the return
};

As side notes,

  • Avoid the #include<bits/stdc++.h> Read more: Why should I not #include <bits/stdc++.h>?

  • Do not practice with using namespace std; Read more: Why is "using namespace std;" considered bad practice?




回答2:


Apart from the std::getline problem already answered:

for(int i=0 ;i<str.length(); i++)
{
    for(int j=0; j<10; j++)
    {
        if(str[i] == a[j])
        {
            // this is the one you do NOT want to print...
            // cout<<str[i];
            // skip instead:
            goto SKIP;
        }
    }
    std::cout << str[i]; // output the one NOT skipped...
    SKIP: (void)0;
}

OK, don't want to start any discussion about usage of goto, there are many ways to avoid it, e. g. by packing the inner for loop into a separate (inline) function. You can have it easier, though, as there already exists such a function; code gets even easier with a range-based for loop:

for(auto c : str)
{
    if(!strchr("aeiouAEIOU", c))
    {
        std::cout << c;
    }
}

strchr (from cstring) returns a pointer to the first character in the string equal to the reference character - or nullptr if not found...

To really remove the vowels from the string in a modern C++ way, consider this:

str.erase(std::remove_if(
        str.begin(), str.end(),
        [](char c) { return strchr("aeiouAEIOU", c) != nullptr; }
    ), str.end());



回答3:


Your code probably should looks like (please see comments inline):

#include <iostream>
#include <string>
using namespace std;

int main() {
    string vowels = "aeiouAEIOU";

    int n;
    cin>>n; // assume this stands for line count

    while(n-- >= 0)
    {
        string str, result;
        getline(cin, str);

        for(int i=0 ;i<str.length(); i++)
        {
            if (vowels.find(str[i]) != std::string::npos)
                result += str[i];   // add character to result if it is not consonant
        }
        cout<<result<<"\n"; // print result
    }

    return 0;
}


来源:https://stackoverflow.com/questions/50714940/how-to-remove-consonants-from-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!