[英]Counting number of syllables in a word, but taking into account that any vowels right next to each other in a word count as one single syllable
通過制作一個簡單的嵌套for循環,我已經能夠計算出單詞中的音節數,但無法弄清楚如何重寫這樣的算法,以確保單詞中任意多個元音彼此相鄰而僅算一個音節。 我只遇到了另一個使用指針的示例,我的問題是,是否有其他方法,因為我本周剛開始學習指針,並且不確定如何正確使用它們。
到目前為止,這是我的程序:
#include <iostream>
#include <string>
using namespace std;
void indexfx(string sentence);
int main(void)
{
string user;
cout << "\n\nPlease Enter a Sentence: ";
getline(cin, user);
indexfx(user);
return 0;
}
void indexfx(string sentence)
{
string vowels = "aeiouy";
int syllables = 0;
for(unsigned int i = 0; i < sentence.size(); i++)
{
for(unsigned int j = 0; j < vowels.size(); j++)
{
if(sentence[i] == vowels[j]
{
syllables++;
}
}
}
cout << syllables;
}
這是一個狀態機。
Vowel Consonant EndOfWord
C V C End
V V C* End*
其中*
表示“增加音節數”。 從狀態C
開始。
測試:
a*da*m ma*da*m he*llo* chi*cke*n
我們可以直接實現此狀態機:
int count_syllables( std::string s ) {
int count = 0;
char state = 'c';
for (auto c : s ) {
switch(state) {
case 'c': {
break;
}
case 'v': {
if (!IsVowel(c)) ++count;
break;
}
}
state = IsVowel(c)?'v':'c';
}
if (state == 'v') ++count;
return count;
}
現在我們只需要編寫IsVowel
。
bool IsVowel(char c) {
static const std::string vowels = "aeiouy";
return vowels.find(c) != std::string::npos;
}
如果找到元音,請不要立即增加音節數。 而是要有一個標志,表明您已找到一個元音。 由於您還沒有時間進行搜索,因此它以false開頭。 如果找到一個,將其翻轉為真並跳出元音循環。
還有另一個標記,可以記住前一個字母是否是元音。 現在僅在當前字母是元音而不是前一個字母的情況下才增加音節數。
在重新啟動字母循環之前,請記住,在最底部,下一個循環中最后一個字母的元音是當前循環中當前字母的元音。
請注意,此答案只是使您的代碼達到您想要的狀態:忽略連續的元音。 該算法本身不是找到音節數的可靠方法,因為英語在這方面有點瘋狂。 有關更多詳細信息,請參見單詞中的音節計數 。
通過使用std::string
方法,您可以執行以下操作:
void indexfx(const std::string& sentence)
{
const std::string vowels = "aeiouy";
int syllables = 0;
std::string::size_type offset = 0;
while (offset != std::string::npos) {
offset = sentence.find_first_of(vowels, offset);
if (offset == std::string::npos) { break; }
++syllables;
offset = sentence.find_first_not_of(vowels, offset);
}
std::cout << syllables << std::endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.