这是一个快速的建议的链接 - 有可能是更好的方法,但我喜欢这一个。
首先,一定要“知道”一个词是由什么组成的。让我们假设它仅由字母组成。其余所有内容,即标点符号或“空格”,都可以视为分隔符。然后,你的“系统”有两个状态: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