原始字面量

原始字面量

在 C++11 中添加了定义原始字符串的字面量,定义方式为:R "xxx(原始字符串)xxx"()两边的字符串可以省略。
原始字面量 R 可以直接表示字符串的实际含义,而不需要额外对字符串做转译等操作。

在编程过程中,使用的字符串中常带有一些特殊字符,对于这些字符往往要做的处理,使用了原始字面量可以轻松的解决这个问题,比如打印路径:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
using namespace std;

int main()
{
string str = "D:\hello\world\test.text";
cout << str << endl;
string str1 = "D:\\hello\\world\\test.text";
cout << str1 << endl;
string str2 = R"(D:\hello\world\test.text)";
cout << str2 << endl;

return 0;
}

D:\hello\world\test.text\h\w 转译失败,对应的字符会原样输出。
D:\\hello\\world\\test.text 中路径的间隔符为 \,但是这个字符又是转译字符,因此将其转译,最终才能得到一个没有特殊含义的普通字符 \
R"(D:\hello\world\test.text)" 使用了原始字面量 R() 中的内容就是描述路径的原始字符串,无需做任何处理。

强调一个细节R "xxx(原始字符串)xxx" 中,原始字符串必须用括号 () 括起来,两边的字符串在解析的时候是会被忽略的,因此一般不用指定。
如果在 () 前后指定了字符串,那么前后的字符串必须相同,否则会出现语法错误。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>
using namespace std;

int main()
{
string str1 = R"(D:\hello\world\test.text)";
cout << str1 << endl;
string str2 = R"luffy(D:\hello\world\test.text)luffy";
cout << str2 << endl;
// string str3 = R"luffy(D:\hello\world\test.text)robin"; // 语法错误,编译不通过
// cout << str3 << endl;

return 0;
}

参考资料

https://subingwen.cn/cpp/R/


原始字面量
https://lcf163.github.io/2021/09/12/原始字面量/
作者
乘风的小站
发布于
2021年9月12日
许可协议