C++-在搜索带下划线的字符串时,行分析器会暂停

C++ - Line parser stalls when searching for string with underscore

本文关键字:分析器 暂停 字符串 搜索 下划线 C++-      更新时间:2023-10-16

我编写了一个函数,该函数解析文本文件中的一行,并将cerain关键字替换为列表中相应的关键字。

代码如下:

std::string __iec_parse_cl(const std::string &line){
    std::string ret = line;
    static const size_t num_tokens = 6;
    static const char *tokens_search[6]{
        filled ...
    };
    static const char *tokens_replace[6]{
        filled ...
    };
    for(size_t x = 0; x < num_tokens; x++){
        size_t yolo;
        do{
            yolo = ret.find(tokens_search[x];
            if(yolo != std::string::npos){
                ret.erase(yolo, strlen(tokens_search[x]));
                ret.insert(yolo, tokens_replace[x]);
            }
        } while(yolo != std::string::npos);
    }
    return ret;
}

当我解析如下所示的令牌时:globalid并将其替换为:get_global_id一切都很好。。。

但是当我试图解析一个看起来像这样的令牌时:global_id并尝试将其替换为:get_global_id程序在函数中的某个位置暂停:/

是什么原因造成的?

这是因为您的搜索需要在替换之后开始。如果你在每次替换后打印出你的字符串,你会看到它有get_global_idget_get_global_idget_get_get_global_id等。

你需要做的是告诉find在你最后一次更换后开始。

    size_t yolo = 0;
    do{
        yolo = ret.find(tokens_search[x], yolo);
        if (yolo != std::string::npos){
            ret.erase(yolo, strlen(tokens_search[x]));
            ret.insert(yolo, tokens_replace[x]);
            yolo += strlen(tokens_replace[x]);
        }
    } while(yolo != std::string::npos);

如果您的代币和它们的替代品之间存在其他重叠,那么这样做也可以防止其他问题。