Flutter Dart 里有没有 类似sprintf 字符串拼接方法

14 min read

在Dart中,您可以使用字符串插值来进行字符串拼接。字符串插值包含在简单的括号中,并使用${}来引用变量或表达式。例如:

String name = 'Tom';
String message = 'Hello, $name!';
print(message); // 输出 "Hello, Tom!"

您还可以使用格式化字符串来进行更高级的字符串插值,类似于sprintf。Dart的字符串支持C语言风格的格式说明符,如% d、% s、% f等。例如:

int apples = 3;
int oranges = 5;
print('I have $apples apples and $oranges oranges.'); // 输出 "I have 3 apples and 5 oranges."
print('I have ${apples + oranges} fruits.'); // 输出 "I have 8 fruits."

double price = 12.34;
print('The price is \$${price.toStringAsFixed(2)}'); // 输出 "The price is $12.34"

此外,Dart还提供了一个类似于sprintf的强大类库intl。使用intl,您可以将数字、日期、时间和货币格式化为特定语言和地区的字符串。