可以刪除緊接着兩個元音的字符串中的所有字符,而不需要char數組的幫助,而只使用「字符串」庫?刪除緊接兩個元音的字符串的所有字符
例如:
priamo -> iamo
該算法應該是:
- 自行車使串中的for循環從
0
到string.length()-2
防止溢出 - 比較對字符與字符數組包含所有元音
- 使用字符串庫中的「擦除」功能刪除誓言前的位置els
但我不知道如何實現第二點沒有字符數組的幫助。有什麼建議麼?
可以刪除緊接着兩個元音的字符串中的所有字符,而不需要char數組的幫助,而只使用「字符串」庫?刪除緊接兩個元音的字符串的所有字符
例如:
priamo -> iamo
該算法應該是:
0
到string.length()-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));
他們的意思是說沒有字符數組的幫助可能意味着你不能做任何形式的緩衝。當然你可以使用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;
}
如果'const char []'不可接受,'const std :: string元音(「aeiou」)'玩同一個遊戲 – 2012-08-15 16:24:18
注意「元音」的定義取決於語言。 「y」可以被認爲是元音,因爲許多其他的重音版本可以被認爲是不同的。 – 2012-08-15 16:28:26
@EmilioGaravaglia - 的確如此,但對於初學者的練習,我認爲添加複雜的區域設置處理並不是一個好主意。
[字符串::找會可能是你在這種情況下的朋友。](http://www.cplusplus.com/reference/string/string/find/) – 2012-08-15 15:21:21
一旦有人離開,你需要再次檢查嗎?考慮一下。第一次通過會導致aee,第二次通過ee。 – chris 2012-08-15 15:22:16
@chris在'aeee'的情況下,算法應該給我'ee'遞歸地擦除一對元音之前的字符,從零位檢查 – 2012-08-15 15:25:39