Unicode字符串字面量

Unicode字符串字面量

语法

“串字符序列” (1)
L"串字符序列" (2)
u8"串字符序列" (3)
u"串字符序列" (4)
U"串字符序列" (5)
前缀(可选)R"分隔符(原始字符)分隔符" (6)

解释

串字符序列 - 零或更多个串字符的序列. 串字符是下列之一

  • 来自源字符集的字符, 除了双引号", 反斜杠\或换行符
  • 转义序列, 定义于转移序列
  • 通用字符名, 定义于转义序列

前缀 - L, u8, u, U之一
分隔符 - 除了括号, 反斜杠和空格意外的任何源字符所构成的字符序列(可为空, 长度至多16个字符)
原始字符 - 任何字符序列, 但必须不含闭序列 )分隔符"

(1) 窄多字节字符串字面量. 无前缀字符串字面量的类型是const char[N], 其中N是以执行窄编码的编码单元计的字符串的大小, 包含终止符
(2) 宽字符串字面量.L"…“字符串字面量的类型是const wchar_t[N],其中N是以执行宽编码的编码单元计的字符串的大小, 包含终止符
(3) UTF-8 编码的字符串字面量. u8”…" 字符串字面量类型是const char[N],其中N是以utf-8的编码单元计的字符串的大小, 包含终止符
(4) UTF-16编码的字符串字面量. u"…" 字符串字面量类型是const char[N],其中N是以utf-16的编码单元计的字符串的大小, 包含终止符
(5) UTF-32编码的字符串字面量. U"…" 字符串字面量类型是const char[N],其中N是以utf-32的编码单元计的字符串的大小, 包含终止符
(6) 原始字符串字面量. 用于避免转义任何字符.分割符间的任何内容都成为字符串的一部分. 若存在前缀则具有上述相同的含义.

示例

#include <iostream>
#include <string>
#include <cstring>

char array1[] = "Foo" "bar";
char array2[] = {
    
    'F', 'o', 'o', 'b', 'a', 'r', '\0'};

const char* s1 = R"foo(
Hello
  World
)foo";

const char* s2 = "\nHello\n  World\n";
const char* s3 = "\n"
                "Hello\n"
                "  World\n";

const wchar_t* s4 = L"test1";
const char* s5 = u8"test1";
const char16_t* s6 = u"test2";
const char32_t* s7 = U"test2";


int main() {
    
    
    std::cout << array1 << '\n';
    std::cout << array2 << '\n';
    std::cout << s1 << s2 << s3;
    std::cout << strlen(s1) << "," << strlen(s2)<< "," << strlen(s3) << std::endl;
    std::cout << "----wchar_t----" << std::endl;
    std::wcout << s4 << ":" << std::endl;
    std::cout << "----utf8----" << std::endl;
    std::cout << s5 << std::endl;
    std::cout << "----utf16----" << std::endl;
    std::wcout << s6 << std::endl;

    std::cout << "----utf32----" << std::endl;
    std::wcout << s7 << std::endl;
    return 0;
}

输出

Foobar
Foobar

Hello
  World

Hello
  World

Hello
  World
15,15,15
----wchar_t----
test1:
----utf8----
test1
----utf16----
0x5613ee8ab0a6
----utf32----
0x5613ee8ab0b4

解释

  • 输出s1,s2,s3的大小都是15.

猜你喜欢

转载自blog.csdn.net/rosemary512/article/details/113383371