這是一個快速的建議的鏈接 - 有可能是更好的方法,但我喜歡這一個。
首先,一定要「知道」一個詞是由什麼組成的。讓我們假設它僅由字母組成。其餘所有內容,即標點符號或「空格」,都可以視爲分隔符。然後,你的「系統」有兩個狀態:1)完成一個單詞,2)跳過分隔符。
您可以免費運行跳過分隔符代碼來開始您的代碼。然後你輸入你將要保留的「完成一個單詞」狀態,直到下一個分隔符或整個字符串的結尾(在這種情況下,你退出)。當它發生時,你已經完成了一個單詞,所以你將你的單詞計數增加1,然後進入「跳過分隔符」狀態。循環繼續。
僞類似C的代碼:如果所述讀取的字符是在[A-ZA-Z_]例如,否則返回假
char *str;
/* someone will assign str correctly */
word_count = 0;
state = SKIPPING;
for(c = *str; *str != '\0'; str++)
{
if (state == SKIPPING && can_be_part_of_a_word(c)) {
state = CONSUMING;
/* if you need to accumulate the letters,
here you have to push c somewhere */
}
else if (state == SKIPPING) continue; // unneeded - just to show the logic
else if (state == CONSUMING && can_be_part_of_a_word(c)) {
/* continue accumulating pushing c somewhere
or, if you don't need, ... else if kept as placeholder */
}
else if (state == CONSUMING) {
/* separator found while consuming a word:
the word ended. If you accumulated chars, you can ship
them out as "the word" */
word_count++;
state = SKIPPING;
}
}
// if the state on exit is CONSUMING you need to increment word_count:
// you can rearrange things to avoid this when the loop ends,
// if you don't like it
if (state == CONSUMING) { word_count++; /* plus ship out last word */ }
函數can_be_part_of_a_word返回true。
(它應該工作如果我沒有做過一些嚴重的錯誤與厭惡的教誨)
你不能使用正則表達式嗎? – danijar
順便說一句:代替'||',你可能需要使用'&&'。 (或者:將'!='改爲'==',並交換if {}和其他{}體)。 – wildplasser