所謂原始字符串(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),人民郵電出版社。