所谓原始字符串(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 // oristr.cpp -- print original string 2 #include <iostream> 3 4 using std::cout; 5 using std::endl; 6 7 int 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),人民邮电出版社。