计算c++中特定字符串的出现次数

count occurrences of specific strings in c++

本文关键字:字符串 c++ 计算      更新时间:2023-10-16

我有一个c++项目来计算输入文件的LLOC,该文件是由代码生成器生成的文件,由一系列函数组成,分别表示F1(), F2(),…, Fn(),然后是主程序和控制结构,如if, while, do, switch等,我们应该计算主程序+函数+分号+方程式+ if语句+ switch语句+ while语句+ for语句的数量。例如,我可以很容易地数出;使用find函数,但我如何计算函数的数量?是否有办法计算子字符串F*(,这意味着每个以F开始并以(结束的子字符串?

下面是我计算分号数目的代码:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char ** argv) {
    ifstream testfile;
    std::string stringline;
    std::string str2(";");
    size_t found;
    int positioncount = 0;
    char arry[100];
    testfile.open("program.cpp");
    while (!testfile.eof()) {
        testfile.getline(arry, 50);
        stringline = arry;
        if (stringline.find(str2) != std::string::npos) {
            positioncount++;
        }
    }
    cout << "n" << positioncount;
    testfile.close();
    return 0;
} 

由于代码是机器生成的,您可以对其进行假设,从而使工作更容易:例如没有注释,没有包含看起来像代码的字符串,没有嵌套类等。

可以让你摆脱基本的正则表达式加上计数大括号。现代c++有内置的正则表达式,你可能想要查看它,比如你的函数名。

计数次数通常使用映射完成(参见http://www.cplusplus.com/reference/map/map/?kw=map)。