你如何在 Dart 中打印美元符号 $ [英] How do you print a dollar sign $ in Dart
问题描述
我需要在 Dart 中实际打印一个美元符号,在变量之前.例如:
I need to actually print a Dollar sign in Dart, ahead of a variable. For example:
void main()
{
int dollars=42;
print("I have $dollars."); // I have 42.
}
我希望输出为:我有 42 美元.我怎样才能做到这一点?谢谢.
I want the output to be: I have $42. How can I do this? Thanks.
推荐答案
Dart 字符串可以是原始的或...不是原始的(正常的?熟的?解释的?没有正式的名称).我将在这里使用解释",因为它描述了您遇到的问题.
Dart strings can be either raw or ... not raw (normal? cooked? interpreted? There isn't a formal name). I'll go with "interpreted" here, because it describes the problem you have.
在原始字符串中,"$" 和 "" 没有什么特别的意思,它们只是其他字符一样.在解释的字符串中,$"开始插值,"开始转义.
In a raw string, "$" and "" mean nothing special, they are just characters like any other. In an interpreted string, "$" starts an interpolation and "" starts an escape.
由于您想要对$dollars"进行插值,因此您不能按字面意思使用$",因此您需要对其进行转义:
Since you want the interpolation for "$dollars", you can't use "$" literally, so you need to escape it:
int dollars = 42;
print("I have $$dollars.");
如果不想使用转义符,可以将原始部分和解释部分的字符串组合起来:
If you don't want to use an escape, you can combine the string from raw and interpreted parts:
int dollars = 42;
print(r"I have $" "$dollars.");
两个相邻的字符串文字合并为一个字符串,即使它们是不同类型的字符串.
Two adjacent string literals are combined into one string, even if they are different types of string.
这篇关于你如何在 Dart 中打印美元符号 $的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!