c++ - 从字符串中删除行注释

标签 c++ string c++11

我正在编写一个文本解析器,它需要能够从行中删除注释。我使用的是一种相当简单的语言,其中所有注释都由 # 字符启动,之后删除所有内容会很简单,但我必须处理 # 在字符串内部的可能性。

因此,我的问题是,给定一个字符串,例如
Value="字符串#1";"字符串#2"; # 这是一个由 "-delimited strings, "Like this"
我怎样才能最好地提取子字符串
Value="String#1";"String#2";(注意尾随空格)

请注意,注释可能包含引号,而且整行可能会选择 "和 ' 分隔符,尽管它会在整行中保持一致。如果它很重要,这是事先知道的。字符串中的引号将被\

转义

最佳答案

std::string stripComment(std::string str) {
    bool escaped = false;
    bool inSingleQuote = false;
    bool inDoubleQuote = false;
    for(std::string::const_iterator it = str.begin(); it != str.end(); it++) {
         if(escaped) {
             escaped = false;
         } else if(*it == '\\' && (inSingleQuote || inDoubleQuote)) {
             escaped = true;
         } else if(inSingleQuote) {
             if(*it == '\'') {
                 inSingleQuote = false;
             }
         } else if(inDoubleQuote) {
             if(*it == '"') {
                 inDoubleQuote = false;
             }
         } else if(*it == '\'') {
             inSingleQuote = true;
         } else if(*it == '"') {
             inDoubleQuote = true;
         } else if(*it == '#') {
             return std::string(str.begin(), it);
         }
    }
    return str;
}

编辑:或者更教科书的 FSM,

std::string stripComment(std::string str) {
    int states[5][4] = {
    //      \  '  "
        {0, 0, 1, 2,}
        {1, 3, 0, 1,},  //single quoted string
        {2, 4, 2, 0,},  //double quoted string
        {1, 1, 1, 1,},  //escape in single quoted string
        {2, 2, 2, 2,},  //escape in double quoted string
    };
    int state = 0;
    for(std::string::const_iterator it = str.begin(); it != str.end(); it++) {
        switch(*it) {
            case '\\':
                state = states[state][1];
                break;
            case '\'':
                state = states[state][2];
                break;
            case '"':
                state = states[state][3];
                break;
            case '#':
                if(!state) {
                    return std::string(str.begin(), it);
                }
            default:
                state = states[state][0];
        }          
    }
    return str;
}

states 数组定义了 FSM 状态之间的转换。

第一个索引是当前状态,0123,或者4

第二个索引对应字符,\'",或者其他字符。

根据当前状态和字符,数组告诉下一个状态。

仅供引用,这些假定反斜杠转义字符串中的任何字符。您至少需要它们来转义反斜杠,这样您就可以拥有一个以反斜杠结尾的字符串。

关于c++ - 从字符串中删除行注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20626009/

相关文章:

c++ - 在 ctor 的初始化列表中使用算术是否稳定?

c++ - std::allocate_shared 使用什么类型来分配内存?

c++ - 具有指向派生对象 : How to tell both of each other's existence? 的指针的基类

C 指针数组未按预期打印,它用最后一个输入替换所有内容

delphi - PChar ('' ) 是否保证是指向 #0 (不是 nil)的指针?

python - 在 PYTHON 中用另一个数字替换一个数字

C++11 原子 x86 内存排序

c++ - 如何将 ifstream 作为参数传递给 std::thread 函数?

c++ - 告诉 gcc 优化器全局函数中的值已更改

c++ - 结构 vector 上的 MemCpy