使用C++计算字符串中字母数字单词数量的最有效方法

Most efficient way to count amount of alphanumeric words within a string using C++

本文关键字:单词数 方法 有效 数字 计算 C++ 字符串 使用      更新时间:2023-10-16

让一个单词定义为任何连续的字母数字字符串。任何非字母数字的单词都可以解析。示例

"嗨,我的第一个name@is@Kevin:)">

输出:6

我知道可以使用for循环简单地遍历字符串,但使用c++11库的全部范围返回正确输出的最有效方法是什么?

我当前的迭代:

int findWords(string line) {
regex AN("[[:alnum:]]");
int count = 0;
bool state = false;
for (char c : line) {
string s(1, c);
bool match = regex_match(s, AN);
if (match && !state) {
state = true;
}
else if (!match && state) {
count++;
state = false;
}
else {
continue;
}
}
if (state == true) { //won't count last word otherwise
count++;
}
return count;
}

据我所知,c++库中并没有专门的函数来计算仅由字母数字组成的单词。例如,istream::iteratordistance结合使用时,会将用空格分隔的"单词"计数,但会将he is aged 45计数为4个单词。也可以考虑strtok或正则表达式,但开销远不止一个简单的循环。因此,例如,请尝试以下操作。除非您在程序执行过程中使用这个方法十亿次,否则它的性能应该足够好。如果没有,请告诉我:-)。给你:

#include <iostream>
int main()
{
string line = "Hi my 1st name@is@Kevin :)";
bool isInAlphaMode = false;
int count = 0;
const char* str = line.c_str();
while (char c = *str) {
if (isalpha(c) && !isInAlphaMode) {
count++;
isInAlphaMode = true;
}
else if (!isalpha(c) && isInAlphaMode) {
isInAlphaMode = false;
}
str++;
}
printf("string '%s' contains %d words", line.c_str(), count);
// output: string 'Hi my 1st name@is@Kevin :)' contains 6 words
return 0;
}