C++ Raw String是C++ 11提供的原始(未加工)的字符串的用法。
语法:
std::string s1 = R"NOT_PRINT_FLAG(String content)NOT_PRINT_FLAG";
说明(这里“打印”也可能是“使用”):
\n(转义字符)会被打印出来。
在‘(’和‘)’符号之外的部分不会被打印出来。
两头的NOT_PRINT_FLAG需要一致。
可以不写NOT_PRINT_FLAG。
在‘)’符号之后不能使用\n(转义字符),否则会有编译错误。
使用场景:
C++中可以直接打印有转义字符的字符串。
给各种脚本(PYTHON,LUA等)发送脚本代码,让脚本直接执行。
总之,有了C++ Raw String,就可以在C++中嵌入原始的字符串了~
#include <iostream>
#include <string>
int main()
{
std::string s1 = R"NOT_PRINT_FLAG(First Line.\nSecond Line. Also IN the FIRST Line)NOT_PRINT_FLAG";
std::string s2 = R"(First Line.
Second Line. Is REAL Second Line.
Third Line.
End Line
)";
printf("C++ Raw String is raw string\n");
printf("Note: \\n print.\n");
printf(" Out side '(' and ')' not print.\n");
printf(" And If had NOT_PRINT_FLAG, they must be Same as each others.\n");
printf(" Or Do not use NOT_PRINT_FLAG.\n");
printf(" After ')' there Should not had any \\n or like characters.\n");
printf("\n");
printf("s1:\n");
printf(s1.c_str());
printf("\n");
printf("\n");
printf("s2:\n");
printf(s2.c_str());
return 0;
}
/*Output:
C++ Raw String is raw string
Note: \n print.
Out side '(' and ')' not print.
And If had NOT_PRINT_FLAG, they must be Same as each others.
Or Do not use NOT_PRINT_FLAG.
After ')' there Should not had any \n or like characters.
s1:
First Line.\nSecond Line. Also IN the FIRST Line
s2:
First Line.
Second Line. Is REAL Second Line.
Third Line.
End Line
*/
参考:
1.
《String literal》:
https://en.cppreference.com/w/cpp/language/string_literal