format
简介
CPP库: fmt
格式化语法: Format String Syntax
注意: pkg只封装了fmt中core.h的format接口,无法使用一些特殊的格式:如 计时规格 等
基本用法:
- string result = format.format("Hello \n", "world");
- format.print("Hello \n", "world");
组件接口
format.gs
函数原型 | 函数作用 |
---|---|
string format(string fmt, ...) | 根据指定的格式将对象的值转换为字符串并插入到相应位置 |
void print(string fmt, ...) | 直接打印结果 |
样例
// Accessing arguments by position:
write(format.format("{0}, {1}, {2}\n", "a", "b", 10));
// Result: "a, b, c"
write(format.format("{}, {}, {}\n", "a", "b", "c"));
// Result: "a, b, c"
write(format.format("{2}, {1}, {0}\n", "a", "b", "c"));
// Result: "c, b, a"
write(format.format("{0}{1}{0}\n\n", "abra", "cad")); // arguments' indices can be repeated
// Result: "abracadabra"
// Aligning the text and specifying a width:
write(format.format("{:<30}\n", "left aligned"));
// Result: "left aligned "
write(format.format("{:>30}\n", "right aligned"));
// Result: " right aligned"
write(format.format("{:^30}\n", "centered"));
// Result: " centered "
write(format.format("{:*^30}\n\n", "centered")); // use '*' as a fill char
// Result: "***********centered***********"
// Dynamic width:
write(format.format("{:<{}}\n\n", "left aligned", 30));
// Result: "left aligned
// begin @ format
// Dynamic precision:
write(format.format("{:.{}f}\n\n", 3.14, 1));
// Result: "3.1"
// Dynamic precision:
write(format.format("{:.{}f}\n\n", 3.14, 1));
// Result: "3.1"
// Replacing %+f, %-f, and % f and specifying a sign:
write(format.format("{:+f}; {:+f}\n", 3.14, -3.14)); // show it always
// Result: "+3.140000; -3.140000"
write(format.format("{: f}; {: f}\n", 3.14, -3.14)); // show a space for positive numbers
// Result: " 3.140000; -3.140000"
write(format.format("{:-f}; {:-f}\n\n", 3.14, -3.14)); // show only the minus -- same as '{:f}; {:f}'
// Result: "3.140000; -3.140000"
// Replacing %x and %o and converting the value to different bases:
write(format.format("int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}\n", 42));
// Result: "int: 42; hex: 2a; oct: 52; bin: 101010"
// with 0x or 0 or 0b as prefix:
write(format.format("int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}\n\n", 42));
// Result: "int: 42; hex: 0x2a; oct: 052; bin: 0b101010"
// Padded hex byte with prefix and always prints both hex characters:
write(format.format("{:#04x}\n\n", 0));
// Result: "0x00"
// Box drawing using Unicode fill:
format.print(
"┌{0:─^{2}}┐\n"
"│{1: ^{2}}│\n"
"└{0:─^{2}}┘\n\n", "", "Hello, world!", 20);
// Result:
// ┌────────────────────┐
// │ Hello, world! │
// └────────────────────┘