What is a raw string?

不问归期 提交于 2020-03-01 04:45:30

问题


I came across this code snippet in C++17 draft n4713:

#define R "x"
const char* s = R"y"; // ill-formed raw string, not "x" "y"

What is a "raw string"? What does it do?


回答1:


Raw string literals are string literals that are designed to make it easier to include nested characters like quotation marks and backslashes that normally have meanings as delimiters and escape sequence starts. They’re useful for, say, encoding text like HTML. For example, contrast

"<a href=\"file\">C:\\Program Files\\</a>"

which is a regular string literal, with

R"(<a href="file">C:\Program Files\</a>)"

which is a raw string literal. Here, the use of parentheses in addition to quotes allows C++ to distinguish a nested quotation mark from the quotation marks delimiting the string itself.




回答2:


Basically a raw string literal is a string in which the escape characters (like \n \t or \" ) of C++ are not processed. A raw string literal which starts with R"( and ends in )" ,introduced in C++11

prefix(optional) R "delimiter( raw_characters )delimiter"

prefix - One of L, u8, u, U

Thanks to @Remy Lebeau, delimiter is optional and is typically omitted, but there are corner cases where it is actually needed, in particular if the string content contains the character sequence )" in it, eg: R"(...)"...)", so you would need a delimiter to avoid an error, eg: R"x(...)"...)x".

See an example:

#include <iostream>
#include <string> 
using namespace std;

int main()
{
    string normal_str="First line.\nSecond line.\nEnd of message.\n";
    string raw_str=R"(First line.\nSecond line.\nEnd of message.\n)";
    cout<<normal_str<<endl;
    cout<<raw_str<<endl;
    return 0;
}

output:

First line.

Second line.

End of message.

First line.\nSecond line.\nEnd of message.\n




回答3:


Raw string literal. Used to avoid escaping of any character. Anything between the delimiters becomes part of the string. prefix, if present, has the same meaning as described above.

C++Reference: string literal

a Raw string is defined like this:

string raw_str=R"(First line.\nSecond line.\nEnd of message.\n)";

and the difference is that a raw string ignores (escapes) all the special characters like \n ant \t and threats them like normal text.

So the above line would be just one line with 3 actual \n in it, instead of 3 separate lines.

You need to remove the define line and add parentheses around your string to be considered as a raw string.



来源:https://stackoverflow.com/questions/56710024/what-is-a-raw-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!