How to Remove Vowels from a String in C++?

  • 时间:2020-09-23 15:50:46
  • 分类:网络文摘
  • 阅读:127 次

Given a string S, remove the vowels ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’ from it, and return the new string.

Example 1:
Input: “leetcodeisacommunityforcoders”
Output: “ltcdscmmntyfrcdrs”

Example 2:
Input: “aeiou”
Output: “”

S consists of lowercase English letters only.
1 <= S.length <= 1000

Loop and Remove

The usual approach will be looping the string and check each character. Ignore the vowels or otherwise push it to the result string.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
    string removeVowels(string S) {
        string s = "";
        for (const auto &n: S) {
            if (string("aeiou").find(n) == string::npos) {
                s.push_back(n);  // s += n;
            }
        }
        return s;
    }
};
class Solution {
public:
    string removeVowels(string S) {
        string s = "";
        for (const auto &n: S) {
            if (string("aeiou").find(n) == string::npos) {
                s.push_back(n);  // s += n;
            }
        }
        return s;
    }
};

Using Modern C++ std::accumulate()

With the std::accumulate() in Modern C++ e.g. C++14, we need to pass the begin and end iterators, the initial value which is set to a mutable string/vector, and a accmulator function.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
    string removeVowels(string S) {
        return std::accumulate(begin(S), end(S), std::string{}, [](auto &a, auto &b) {
            if (string("aeiou").find(b) == string::npos) {
                return a + b; 
            } 
            return a; // b is vowel, ignore
        });
    }
};
class Solution {
public:
    string removeVowels(string S) {
        return std::accumulate(begin(S), end(S), std::string{}, [](auto &a, auto &b) {
            if (string("aeiou").find(b) == string::npos) {
                return a + b; 
            } 
            return a; // b is vowel, ignore
        });
    }
};

It is worth pointing out that the “” in C++ is interpreted to char* by default, that is why we need to explicitly cast it to string type before using the find() method.

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
金鹰卡通直播-金鹰卡通在线直播观看「高清」  优漫卡通直播-优漫卡通卫视在线直播「高清」  炫动卡通直播-上海炫动卡通卫视直播「高清」  BTV卡酷少儿直播-北京卡酷动画卫视直播「高清」  嘉佳卡通卫视直播-嘉佳卡通直播在线观看「高清」  浙江少儿频道直播-浙江少儿在线直播观看「高清」  广州少儿频道直播-广州少儿在线直播观看「高清」  福建少儿频道直播-福建少儿在线直播观看「高清」  内蒙古少儿频道直播-内蒙古少儿在线直播观看「高清」  劲爆体育直播-劲爆体育在线直播观看「高清」 
评论列表
添加评论