您的位置:首页 > 编程语言 > C语言/C++

C++11中的小细节--字符串的原始字面量

2016-01-13 00:22 901 查看
原始字面量很容易理解,即不进行转义的完整字符串。

最近看了看Python,其中讲到了原始字符串。

Both string and bytes literals may optionally be prefixed with a letter ‘r’ or ‘R’; such strings are called raw strings and treat backslashes as literal characters. As a result, in string literals, ‘\U’ and ‘\u’ escapes in raw strings are not treated specially. Given that Python 2.x’s raw unicode literals behave differently than Python 3.x’s the ‘ur’ syntax is not supported.

例如,原始字符串对于反斜杠不会做特殊的处理:

# Python 程序
print r'C:\nowhere'


即在Python中,原始字符串以r开头。

这样的功能C++会有吗?

C++11不愧称为modern c++,当然会提供原始字符串了。

但是Python里使用的是r,而C++11中使用的是R。

但是需要注意的是:

原始字符串字面量的定义为:R “xxx(raw string)xxx”

其中,原始字符串必须用括号()括起来,括号的前后可以加其他字符串,所加的字符串会被忽略,并且加的字符串必须在括号两边同时出现。

#include <iostream>
#include <string>

int main()
{
// 一个普通的字符串,'\n'被当作是转义字符,表示一个换行符。
std::string normal_str = "First line.\nSecond line.\nEnd of message.\n";

// 一个raw string,'\'不会被转义处理。因此,"\n"表示两个字符:字符反斜杠 和 字母n。
std::string raw_str = R"(First line.\nSecond line.\nEnd of message.\n)";

std::cout << normal_str << std::endl;
std::cout << raw_str << std::endl;
std::cout << R"foo(Hello, world!)foo" << std::endl;

// raw string可以跨越多行,其中的空白和换行符都属于字符串的一部分。
std::cout <<R"(
Hello,
world!
)" << std::endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: