Java - 在字符串中包含变量? [英] Java - Including variables within strings?

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

问题描述

好的,所以我们都应该知道你可以通过这样做把变量包含到字符串中:

Ok, 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.

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

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