如何在字符串中包含变量? [英] How to including variables within strings?

查看:63
本文介绍了如何在字符串中包含变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我们都应该知道你可以通过以下方式将变量包含到字符串中:

So, we all should know that you can include variables into strings by doing:

String string = "A string " + aVariable;

有没有办法做到这一点:

Is there a way to do it like:

String string = "A string {aVariable}";

换句话说:无需关闭引号并添加加号.太不吸引人了.

In other words: Without having to close the quotation marks and adding plus signs. It's very unattractive.

推荐答案

您始终可以使用 String.format(....).即,

You can always use String.format(....). i.e.,

String string = String.format("A String %s %2d", aStringVar, anIntVar);

我不确定这对您是否足够有吸引力,但它可能非常方便.语法与 printf 和 java.util.Formatter 相同.我经常使用它,特别是如果我想显示表格数字数据.

I'm not sure if that is attractive enough for you, but it can be quite handy. The syntax is the same as for printf and java.util.Formatter. I've used it much especially if I want to show tabular numeric data.

这篇关于如何在字符串中包含变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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