In this chapter, you will learn about the newly added string literals like raw string literals and encoded string literals.
After the C++11 standardization, programmer's can able to classify raw string as well as multibyte/wide character string type literals. Here are the two types of String Literals discussed below with code snippets:
Raw String Literals
These types of raw strings allow programmers to define a series of characters by writing precisely its contents like raw character sequence. In this way, you can save a lot of escapes essential for masking special characters. Here's an example of ordinary string literal which represents two backslashes and an n defined as an ordinary string literal as below:
"\\\\n"
and as a raw string literal as follows:
R"(\\n)"
For having a )" inside the raw string, you are free to use a delimiter. So, the complete syntax of a raw string is:
R"delim(...)delim", where delim can be a character except the backslash, whitespaces, and parentheses.
Demonstrating Working of Raw String
Example:
#include <iostream>
using namespace std;
int main()
{
// Normal string
string str1 = "Sample.\nmultiline.\ncontent.\n" ;
// Raw string
string str2 = R"(Sample.\nmultiline.\ncontent.\n)";
// Output
cout << str1 << endl;
cout << str2 << endl;
return 0;
}
Output:
Sample. multiline. content. Sample.\nmultiline.\ncontent.\n
Encoded String Literals
By implementing an encoding prefix, you can classify a special character indoctrination for string literals. The below-mentioned encoding prefixes are defined:
- u8 is used to define a UTF-8 encoding scheme. A UTF-8 string literal usually initialized with the given characters as encoded fixed in UTF-8. The characters contain type const char.
- u is used to defining a string literal having characters of category char16_t.
- U is used to defining a string literal having characters of the form char32_t.
- L is used to define a broad string literal having characters of the form wchar_t.
Example:
const char[] str = L"helloWorld" // defines "helloWorld" as wchar_t string literal
The initial R of a raw string can be preceded by an encoding prefix.