c++ - 如何解析带有原始转义序列的字符串?

标签 c++ string

假设有2个字符串:

string parse(const string& s) {
    // how to write this function?
}

int main() {
    string s1 = R"(hello\n\"this is a string with escape sequences\"\n)";
    string s2 = "hello\n\"this is a string with escape sequences\"\n";
    assert(parse(s1) == s2);
}

我的问题是,除了一些遍历字符串并检查每个可能的转义序列的手工代码之外,如何编写函数 parse() 以使断言成功?是否有任何现有的习语可以做到这一点?

最佳答案

您可以使用字符串流。检查字符串的每个字符是否存在转义的反斜杠“\”字符。找到后,检查下一个字符是否为有效的转义字符。然后将一个字符串写入该转义字符序列的字符串流。

std::string parse(const std::string& s)
{
    std::stringstream  ss{""};

    for(size_t i = 0; i < s.length(); i++)
    {
        if (s.at(i) == '\\')
        {
            switch(s.at(i + 1))
            {
                case 'n':  ss << "\n"; i++; break;
                case '"':  ss << "\""; i++; break;
                default:   ss << "\\";      break;
            }       
        }
        else 
        {
            ss << s.at(i);
        }
    }

    return ss.str();
}

关于c++ - 如何解析带有原始转义序列的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27617903/

相关文章:

python - 统计一个字符是否在字符串中出现 3 次或更多次

python - 在列表的列表中操作字符串

c++ - 从argv [1]转换为char * string后,出现什么问题?

c++ - CMake 错误 : linker command failed with exit code 1 and cpp. o 文件

c++ - std::optional::value_or() - 惰性参数评估

c++ - LLDB:通过控制台为malloc_error_break设置断点

c - C语言删除句子中所有出现的单词的函数

php - 在两个应用程序之间传输大量数据的最快方式

c++ - 'itoa' : function does not take 1 arguments & 'c' : undeclared identifier

Python循环遍历CSS文件中的所有url并替换