字面量后缀总结(二百四十七)"/>
C++之C++11字符串字面量后缀总结(二百四十七)
简介: CSDN博客专家,专注Android/Linux系统,分享多mic语音方案、音视频、编解码等技术,与大家一起成长!
优质专栏:Audio工程师进阶系列【原创干货持续更新中……】🚀
人生格言: 人生从来没有捷径,只有行动才是治疗恐惧和懒惰的唯一良药.
1.前言
本篇目的:理解C++11字符串字面量后缀总结。
2.C++11字符串字面量后缀介绍
-
C++11引入了字符串字面量后缀,可以用于在字符串字面量的末尾添加后缀以指定其类型。这样做的好处是增强了类型安全性,使得字符串字面量可以根据后缀的类型进行解析和处理。
-
以下是一些常用的字符串字面量后缀:
-
后缀"s":用于表示字符串字面量,其类型为
const char[]
。例如:"hello"s表示类型为const char[]
的字符串。 -
后缀"u8":用于表示UTF-8字符串字面量,其类型为
const char[]
。例如:"你好"u8表示类型为const char[]
的UTF-8字符串。 -
后缀"u":用于表示宽字符字符串字面量,其类型为
const wchar_t[]
。例如:L"hello"u表示类型为const wchar_t[]
的宽字符字符串。 -
后缀"U":用于表示Unicode字符串字面量,其类型为
const char32_t[]
。例如:U"hello"表示类型为const char32_t[]
的Unicode字符串。 -
后缀"L":用于表示宽字符串字面量,其类型为
const wchar_t[]
。例如:L"hello"表示类型为const wchar_t[]
的宽字符串。
这些字符串字面量后缀提供了更灵活的字符串字面量表示方式,可以根据需要选择适合的类型和编码方式。
-
使用
s
后缀表示字符串字面量:auto str1 = "hello"s; // 类型为std::string
-
使用
u8
后缀表示UTF-8字符串字面量:auto str2 = u8"你好"; // 类型为const char[]
-
使用
u
后缀表示宽字符字符串字面量:auto str3 = L"hello"u; // 类型为const wchar_t[]
-
使用
U
后缀表示Unicode字符串字面量:auto str4 = U"hello"; // 类型为const char32_t[]
-
使用
L
后缀表示宽字符串字面量:auto str5 = L"hello"; // 类型为const wchar_t[]
3.代码实例
1.后缀"s"
#include <iostream>
#include <string>
#include <string_view>using namespace std::literals::string_literals;int main() {std::string message = "Hellow"s;std::cout << message << std::endl;return 0;
}
1.后缀"u8": 表示字符串字面量,其类型为const char[]
。例如:"hello"s表示类型为const char[]
的字符串。
#include <iostream>
#include <string>
#include <string_view>using namespace std::literals::string_literals;int main() {std::string message = "Hellow"u8;std::cout << message << std::endl;return 0;
}
2.后缀"u":表示UTF-8字符串字面量,其类型为const char[]
。例如:"你好"u8表示类型为const char[]
的UTF-8字符串。
#include <iostream>
#include <string>
#include <string_view>using namespace std::literals::string_literals;int main() {std::string message = "Hellow"s;std::cout << message << std::endl;return 0;
}
3.后缀"U":表示宽字符字符串字面量,其类型为const wchar_t[]
。例如:L"hello"u表示类型为const wchar_t[]
的宽字符字符串。
#include <iostream>
#include <string>
#include <string_view>using namespace std::literals::string_literals;int main() {std::string message = "Hellow"s;std::cout << message << std::endl;return 0;
}
4.后缀"s"
#include <iostream>
#include <string>
#include <string_view>using namespace std::literals::string_literals;int main() {std::string message = "Hellow"s;std::cout << message << std::endl;return 0;
}
5.后缀"L":表示宽字符串字面量,其类型为const wchar_t[]
。例如:L"hello"表示类型为const wchar_t[]
的宽字符串。
#include <iostream>
#include <string>
#include <string_view>using namespace std::literals::string_literals;int main() {std::string message = "Hellow"s;std::cout << message << std::endl;return 0;
}
更多推荐
C++之C++11字符串字面量后缀总结(二百四十七)
发布评论