C++ Raw String用法小结

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值