试试这个for proper console in:
int main()
{
int n;
std::cin >> n;
std::cin.ignore(); // fix
/* remaining code */
return 0;
}
> 查找字符串中的元音
在字符串中查找元音的方法是使用std::binary_search 元音表中给定字符串的每个字符。
- 制作一个由所有元音组成的
char排序数组(即元音数组)。
- 对于输入字符串的每个
char,std::binary_search 在
元音数组。
- 如果
std::binary_search返回true(意味着char是元音),打印字符串的char。
以下是示例代码! (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;
}
输出:
a o u I I O
> 删除字符串中的元音
如下使用erase-remove idiom(直到c++17†)。
- 制作一个由所有元音组成的
char排序数组(即元音数组)。
- 使用
std::remove_if,收集指向元音字符的迭代器。可以使用 lambda 函数作为 std::remove_if 的谓词,其中std::binary_search 用于检查字符串中的char 是否存在于元音数组中。
- 使用
std::string::erase,从字符串中删除所有收集到的字符(即元音)。
以下是示例代码! (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;
}
输出:
Hll Wrld
† 由于c++20,因此可以使用std::erase_if,即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;
}
> 删除字符串中的辅音
要从给定字符串中删除辅音,在上面的predicate 中否定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
};
作为旁注,