C++11原始字符串的表⽰
所谓原始字符串(raw string)就是字符表⽰的就是⾃⼰,引号和斜杠均⽆需\进⾏转义,这在需要输出很多引号和斜杠代码中很⽅便。原始字符串是C++11新增的⼀个功能,程序中使⽤R“(a string)”来标识原始字符串:
cout << "I print \'\\\', \"\\n\" as I like." << endl;  // 屏幕显⽰: I print '\', "\n" as I like.
cout << R"(I print '\', "\n" as I like.)" << endl;  // 屏幕显⽰: I print '\', "\n" as I like.
C++11原始字符串同时包含其它特点:
1. 字符串中的换⾏符将在屏幕上如实显⽰。
2. 在表⽰字符串开头的"和(之间可以添加其它字符,不过必须在表⽰字符串结尾的)和"之间添加同样的字符。
第⼆个特性允许在字符串中使⽤任何和原始字符串边界标识不同的任意字符组合,⽽不⽤担⼼提前结束原始字符串,⽐如使⽤“).
贴上测试代码:
1// oristr.cpp -- print original string
2 #include <iostream>
3
4using std::cout;
5using std::endl;
6
7int main(){
8    cout << "I print \'\\\', \"\\n\" as I like." << endl;
9    cout << R"(I print '\', "\n" as I like.)" << endl;
10    cout << R"(I print '\',
11"\n"as I like.)" << endl;
12    cout << R"haha(I print '\', "\n" and )"as I like.)haha" << endl;
13 }
程序输出如下:
I print '\', "\n" as I like.
I print '\', "\n" as I like.
默认字符串是什么I print '\',
"\n"as I like.
I print '\', "\n" and )" as I like.
该博客内容参考《C++Primer Plus》中⽂版第六版4.3.5节(p.87),⼈民邮电出版社。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。