删除后面紧跟两个元音的字符串的所有字符

时间:2012-08-15 15:17:16

标签: c++ string

可以删除紧跟着两个元音的字符串的所有字符,而不使用char数组,而只使用“字符串”库?

例如:

priamo -> iamo

算法应该是:

  1. 循环播放从0string.length()-2的for循环的字符串以防止溢出
  2. 将字符对与包含所有元音的字符数组进行比较
  3. 使用字符串库中的“擦除”功能删除元音前的位置
  4. 但我不知道如何在没有字符数组的帮助下实现第二点。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

我建议使用std::adjacent_find

std::string s{"priamo"};
auto is_vowel = [](char c) -> bool {
    static const char vowels[] = "aeiou";
    return std::any_of(std::begin(vowels), std::prev(std::end(vowels)),
        [c](char d) { return c == d; } );
};
auto it = std::adjacent_find(s.crbegin(), s.crend(),
    [&](char c, char d) { return is_vowel(c) && is_vowel(d); }).base();
if (it != s.cbegin())
    s.erase(s.cbegin(), std::prev(it, 2));

答案 1 :(得分:0)

他们的意思是说没有char数组的帮助可能意味着你不能做任何缓冲。当然,您可以使用const char vowels[]="aeiou";

嗯,这可能是错的,但应该给你一个想法和其他人纠正的基础:

string str="priamo";
const char vowels[]="aeiou";
size_t pos=0;
size_t vowels_piled_up=0;
while((pos=str.find_first_of(&vowels[0], pos+vowels_piled_up))!=string::npos)
{
  if((pos+1)+1 >= str.size())//break if it is on the last 2
     break;
  if((strchr(&vowels[0], str[pos+1]))!=NULL)
  {
     str.erase(vowels_piled_up, pos-1-vowels_piled_up);
     pos=0;
     vowels_piled_up+=2;
  }
  else
     ++pos;
}
相关问题