如何在Dart中打印美元符号$ [英] How do you print a dollar sign $ in Dart

查看:744
本文介绍了如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆