gpt4 book ai didi

C++ 转义字符串中出现的\

转载 作者:太空宇宙 更新时间:2023-11-04 14:52:31 24 4
gpt4 key购买 nike

是否有一种简单的方法来转义字符串中所有出现的 \ ?我从以下字符串开始:

#include <string>
#include <iostream>

std::string escapeSlashes(std::string str) {
// I have no idea what to do here
return str;
}

int main () {
std::string str = "a\b\c\d";

std::cout << escapeSlashes(str) << "\n";
// Desired output:
// a\\b\\c\\d

return 0;
}

基本上,我正在寻找 this 的逆函数问题。问题是我无法在字符串中搜索 \,因为 C++ 已经将其视为转义序列。

注意: 我无法首先更改字符串 str。它是从 LaTeX 文件解析而来的。因此,this类似问题的答案不适用。 编辑:由于不相关的问题导致解析失败,这里的问题是关于字符串文字的。

编辑:有一些很好的解决方案可以查找和替换已知的转义序列,例如 this回答。另一种选择是使用 boost::regex("\p{cntrl}")。但是,我还没有找到适用于未知(错误)转义序列的方法。

最佳答案

您可以使用原始字符串文字。参见 http://en.cppreference.com/w/cpp/language/string_literal

#include <string>
#include <iostream>

int main() {
std::string str = R"(a\b\c\d)";

std::cout << str << "\n";
return 0;
}

输出:

a\b\c\d

关于C++ 转义字符串中出现的\,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49426465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com