gpt4 book ai didi

string - 可以将原始字符串修饰符R“()”与字符串变量结合使用吗?

转载 作者:行者123 更新时间:2023-12-04 19:30:07 24 4
gpt4 key购买 nike

例子
例如:

string MyString = "Normal\tString";
cout << MyString << endl;
产生以下内容: "Normal String"
将原始字符串修饰符附加到字符串,如下所示:
string MyString = R"(Normal\tString)";
cout << MyString << endl;
产生以下内容: "Normal\tString"
问题
有没有一种方法可以将原始字符串修饰符附加到包含字符串的变量中,以显示该变量中包含的字符串的原始形式?
string TestString = "Test\tString";
cout << R(TestString) << endl;
这样就得到了: "Test\tString"

最佳答案

Is there a way to append the raw string modifier to a variable containing a string in order to print the raw form of the string contained within the variable?



不。

但是,您可以编写一个函数,以适当的字符串替换转义序列定义的字符,即,将字符串 '\t'替换为字符串 "\\t"

样例程序:
#include <iostream>
#include <string>

// Performs only one substitution of \t.
// Needs to be updated to do it for all occurrences of \t and
// all other escape sequences that can be found in raw strings.
std::string toRawString(std::string const& in)
{
std::string ret = in;
auto p = ret.find('\t');
if ( p != ret.npos )
{
ret.replace(p, 1, "\\t");
}

return ret;
}

int main()
{
std::string TestString = "Test\tString";
std::cout << toRawString(TestString) << std::endl;
}

输出:

Test\tString

关于string - 可以将原始字符串修饰符R“()”与字符串变量结合使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44314910/

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