使用C++计算字符串中字母数字单词数量的最有效方法
Most efficient way to count amount of alphanumeric words within a string using C++
让一个单词定义为任何连续的字母数字字符串。任何非字母数字的单词都可以解析。示例
"嗨,我的第一个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::iterator
与distance
结合使用时,会将用空格分隔的"单词"计数,但会将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;
}
相关文章:
- 初始化具有非默认构造函数的std::数组项的更好方法
- 复制几乎为空的数组的最快方法
- 通过JNI传递数据数组的最快方法是什么
- 在调用接收数组的方法时,模板化数组大小是不是一种糟糕的做法
- 数组元素打印的递归方法
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- C++数组队列实现方法错误
- 寻找一种更好的方法来表示无符号字符数组
- 当您在此单词中搜索单词时调整字符数组的大小?
- 数每个单词的元音
- 在 C++ 中将整数数组转换为位集表示形式的最佳方法?
- 初始化数组、"memset"或" {//value} "的最佳方法是什么?
- 创建异构顶点数据数组的可移植方法
- 打印字符数组地址的正确方法
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- 将字节数组 (uint8_t) 转换为单词数组 (uint16_t),反之亦然
- 应用于单词数组的随机数范围
- 从文件中读取行数、单词数、字符数