原始字面量

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

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

#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:helloworld    est.text
D:\hello\world\test.text
D:\hello\world\test.text
  • 在 D:\hello\world\test.text 中 \h\w转义失败,对应的字符会原样输出,另外\t会识别为为Tab制表符
  • 在 D:\hello\world\test.text 中路径的间隔符为 \ 但是这个字符又是转义字符,因此需要使用转义字符将其转义,最终才能得到一个没有特殊含义的普通字符 \
  • 在 R"(D:\hello\world\test.text)" 使用了原始字面量 R()中的内容就是描述路径的原始字符串,无需做任何处理

通过测试可以看到,使用原始字面量 R 可以直接得到其原始意义的字符串,再看一个输出 HTML 标签的例子:

#include<iostream>
#include<string>
using namespace std;
int main()
{
    
    
    string str = "<html>\
        <head>\
        <title>\
        海贼王\
        </title>\
        </head>\
        <body>\
        <p>\
        我是要成为海贼王的男人!!!\
        </p>\
        </body>\
        </html>";
    cout << str << endl;
    return 0;
}

在 C++11 之前如果一个字符串分别写到了不同的行里边,需要加连接符,这种方式不仅繁琐,还破坏了表达式的原始含义,如果使用原始字面量就变得简单很多,很强直观,可读性强。

#include<iostream>
#include<string>
using namespace std;
int main()
{
    
    
    string str = R"(<html>
        <head>
        <title>
        海贼王
        </title>
        </head>
        <body>
        <p>
        我是要成为海贼王的男人!!!
        </p>
        </body>
        </html>)";
    cout << str << endl;

    return 0;
}

最后强调一个细节:在R “xxx(raw string)xxx” 中,原始字符串必须用括号()括起来,括号的前后可以加其他字符串,所加的字符串会被忽略,并且加的字符串必须在括号两边同时出现

#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;
#if 0
    string str3 = R"luffy(D:\hello\world\test.text)robin";	// 语法错误,编译不通过
    cout << str3 << endl;
#endif

    return 0;
}

测试代码输出的结果为:

D:\hello\world\test.text
D:\hello\world\test.text

通过输出的信息可以得到如下结论:使用原始字面量 R “xxx (raw string) xxx”()两边的字符串在解析的时候是会被忽略的,因此一般不用指定。如果在()前后指定了字符串,那么前后的字符串必须相同,否则会出现语法错误。

猜你喜欢

转载自blog.csdn.net/weixin_38346042/article/details/131510800
今日推荐