Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient C++ way of giving literal meaning to special symbols (") in a C++ string

I want to put this:

<script src = "Script2.js" type = "text/javascript"> < / script>

in a std::string so I append a (\) symbol before every double quotes (") to give it a literal meaning of ", instead of a string demarcation in C++ like this:

std::string jsFilesImport = "<script src = \"Script2.js\" type = \"text/javascript\"> < / script>\""

If I have a big string with many ("), adding (\) for every (") becomes difficult. Is there a simple way to achieve this in C++?

like image 909
codeLover Avatar asked Aug 17 '17 17:08

codeLover


People also ask

What is the string literal in C?

A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string.

Which symbols are used to contain string literals?

A string literal contains a sequence of characters or escape sequences enclosed in double quotation mark symbols. A string literal with the prefix L is a wide string literal.

Is it possible to modify a string literal in C?

The only difference is that you cannot modify string literals, whereas you can modify arrays. Functions that take a C-style string will be just as happy to accept string literals unless they modify the string (in which case your program will crash).


1 Answers

The easiest way is to use a raw string literal:

std::string s = R"x(<script src = "Script2.js" type = "text/javascript"> < / script>)x";
             // ^^^^                                                                ^^^

You just need to take care that the x( )x delimiters aren't used in the text provided inside. All other characters appearing within these delimiters are rendered as is (including newlines). x is arbitrarily chosen, could be something(, )somethingas well.


To prevent further questions regarding this:

No, it's not possible to do1 something like

std::string s = R"resource(
#include "MyRawTextResource.txt"
)resource";

The preprocessor won't recognize the #include "MyRawTextResource.txt" statement, because it's enclosed within a pair of double quotes (").

For such case consider to introduce your custom pre-build step doing the text replacement before compilation.


1)At least I wasn't able to find a workaround. Appreciate if someone proves me wrong about that.

like image 107
user0042 Avatar answered Oct 11 '22 17:10

user0042