第9.12章: string
概述
::fast_io::string 是一段动态的、以空字符结尾的字符序列。本节只讲要点:字符类型变体、concat_fast_io 以及 to<T>。
string 类型还有许多其他操作(查找、修剪、比较等)。你可以先跳过这些细节,需要时再回到附录第9.12.1节。
1. 字符类型变体
| 别名 | 字符类型 | 分配器 |
|---|---|---|
::fast_io::string |
char |
全局(默认) |
::fast_io::wstring |
wchar_t |
全局 |
::fast_io::u8string |
char8_t |
全局 |
::fast_io::u16string |
char16_t |
全局 |
::fast_io::u32string |
char32_t |
全局 |
线程局部分配器的变体位于 ::fast_io::tlc 命名空间:::fast_io::tlc::string、::fast_io::tlc::wstring 等。
2. concat_fast_io — 字符串拼接
concat_fast_io 把它的所有参数格式化进一个新字符串并返回。它是 print 的“产生字符串”版本:
#include <fast_io_dsal/string.h>
#include <fast_io.h>
int main() {
// Concatenate mixed types into a string
::fast_io::string s = ::fast_io::concat_fast_io(
"Hello, ", "user #", 42, " (score: ", 3.14, ")");
// s == "Hello, user #42 (score: 3.14)"
::fast_io::io::println(s);
// concatln_fast_io appends a newline
::fast_io::string line = ::fast_io::concatln_fast_io("done");
// line == "done\n"
// Wide-string variants
::fast_io::wstring ws = ::fast_io::wconcat_fast_io(L"wide: ", 100);
// UTF-8, UTF-16, UTF-32 variants
::fast_io::u8string u8s = ::fast_io::u8concat_fast_io(u8"utf8: ", 100);
::fast_io::u16string u16s = ::fast_io::u16concat_fast_io(u"utf16: ", 100);
::fast_io::u32string u32s = ::fast_io::u32concat_fast_io(U"utf32: ", 100);
}
3. to<T> — 打印的逆过程
to<T> 是 print 的逆操作:它先把参数格式化,再把结果解析成类型 T。可以把它看作一步完成 sprintf 加 sscanf,只不过在编译期就做了优化:
#include <fast_io.h>
int main() {
// Print 42, parse it back as a double
double d = ::fast_io::to<double>(42); // d == 42.0
// Concatenate then parse
::std::size_t n = ::fast_io::to<::std::size_t>(1zu, 23zu); // "1" + "23" -> 123
// In-place version (writes into existing variable)
double x{};
::fast_io::inplace_to(x, "3.14");
// x == 3.14
// Wide-string variants
::std::size_t w = ::fast_io::wto<::std::size_t>(L"42");
}
要点
string、wstring、u8string、u16string、u32string覆盖了所有字符类型。tlc::命名空间提供线程局部分配器的变体。concat_fast_io(args...)把参数格式化成一个新字符串。concatln_fast_io(args...)在末尾追加一个换行。to<T>(args...)先打印,再把结果解析成类型T。inplace_to(t, args...)解析到已有的变量中。- 完整的操作参考见附录第9.12.1节。