程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> C++11中的小細節--字符串的原始字面量

C++11中的小細節--字符串的原始字面量

編輯:C++入門知識

C++11中的小細節--字符串的原始字面量


原始字面量很容易理解,即不進行轉義的完整字符串。

最近看了看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 
#include 

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 <
 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved