字符串变量插值Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6389827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:32:21  来源:igfitidea点击:

String variable interpolation Java

javastring-interpolation

提问by cmcculloh

String building in Java confounds me. I abhore doing things like:

Java 中的字符串构建让我感到困惑。我讨厌做这样的事情:

url += "u1=" + u1 + ";u2=" + u2 + ";u3=" + u3 + ";u4=" + u4 + ";";
url += "x=" + u1 + ";y=" + u2 + ";z=" + u3 + ";da1=" + u4 + ";";
url += "qty=1;cost=" + orderTotal + ";ord=" + orderId + "?";

Or, using StringBuilder, something like this:

或者,使用 StringBuilder,像这样:

    url.append("u1=");
    url.append(u1);
    url.append(";u2=");
    url.append(u2);
    url.append(";u3=");
    url.append(u3);
    url.append(";u4=");
    url.append(u4);
    url.append(";");
    url.append("x=");
    url.append(u1);
    url.append(";y=");
    url.append(u2);
    url.append(";z=");
    url.append(u3);
    url.append(";da1=");
    url.append(u4);
    url.append(";");
    url.append("qty=1;");
    url.append("cost=");
    url.append(orderTotal);
    url.append(";ord=");
    url.append(orderId);
    url.append("?");

SURELY I'm missing something. There has GOT to be a better way. Something like:

当然我错过了一些东西。必须有更好的方法。就像是:

Instead of:

代替:

urlString += "u1=" + u1 + ";u2=" + u2 + ";u3=" + u3 + ";u4=" + u4 + ";";

do:

做:

urlString += Interpolator("u1=%s;u2=%s;u3=%s;u4=%s;", u1, u2, u3, u4);

or:

或者:

urlStringBuilder.append(Interpolator("u1=%s;u2=%s;u3=%s;u4=%s;", u1, u2, u3, u4));

采纳答案by Jon Skeet

If you're using Java 5 or higher, you can use String.format:

如果您使用的是 Java 5 或更高版本,则可以使用String.format

urlString += String.format("u1=%s;u2=%s;u3=%s;u4=%s;", u1, u2, u3, u4);

See Formatterfor details.

详情请参阅Formatter

回答by unholysampler

String.format()to the rescue!!

String.format()救命!!

回答by Jan Bodnar

Note that there is no variable interpolation in Java. Variable interpolation is variable substitution with its value inside a string. An example in Ruby:

请注意,Java 中没有变量插值。变量插值是变量替换,其值在字符串中。Ruby 中的示例:

#!/usr/bin/ruby

age = 34
name = "William"

puts "#{name} is #{age} years old" 

The Ruby interpreter automatically replaces variables with its values inside a string. The fact, that we are going to do interpolation is hinted by sigil characters. In Ruby, it is #{}. In Perl, it could be $, % or @. Java would only print such characters, it would not expand them.

Ruby 解释器会自动用字符串中的值替换变量。事实上,我们要进行插值是由印记字符暗示的。在 Ruby 中,它是 #{}。在 Perl 中,它可以是 $、% 或 @。Java 只会打印这些字符,不会扩展它们。

Variable interpolation is not supported in Java. Instead of this, we have string formatting.

Java 不支持变量插值。取而代之的是,我们有字符串格式。

package com.zetcode;

public class StringFormatting 
{
    public static void main(String[] args) 
    {
        int age = 34;
        String name = "William";

        String output = String.format("%s is %d years old.", name, age);

        System.out.println(output);
    }
}

In Java, we build a new string using the String.format() method. The outcome is the same, but the methods are different.

在 Java 中,我们使用 String.format() 方法构建一个新字符串。结果是一样的,只是方法不同。

See http://en.wikipedia.org/wiki/Variable_interpolation

http://en.wikipedia.org/wiki/Variable_interpolation

EditAs of 2019, JEP 326(Raw String Literals) was withdrawn and superseeded by JEP 355(Text Blocks). The latter tries to introduce "Text Blocks" into the language:

编辑截至 2019 年,JEP 326(原始字符串文字)已被JEP 355(文本块)撤回并取代。后者试图在语言中引入“文本块”:

A text block is a multi-line string literal that avoids the need for most escape sequences, automatically formats the string in a predictable way, and gives the developer control over format when desired.

文本块是一种多行字符串文字,它避免了大多数转义序列的需要,以可预测的方式自动格式化字符串,并在需要时让开发人员控制格式。

However, still no string interpolation:

但是,仍然没有字符串插值

Non-Goals: Text blocks do not directly support string interpolation. Interpolation may be considered in a future JEP.

非目标:文本块不直接支持字符串插值。在未来的 JEP 中可能会考虑插值。

回答by Jimmy Kane

Just to add that there is also java.text.MessageFormatwith the benefit of having numeric argument indexes.

只是补充一点,还有java.text.MessageFormat具有数字参数索引的好处。

Appending the 1st example from the documentation

附加文档中的第一个示例

int planet = 7;
String event = "a disturbance in the Force";

String result = MessageFormat.format(
    "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
    planet, new Date(), event);

Result:

结果:

At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7.

回答by LEMUEL ADANE

You can use Kotlin, the Super (cede of) Java for JVM, it has a nice way of interpolating strings like those of ES5, Ruby and Python.

您可以使用 Kotlin,它是 JVM 的超级(割让)Java,它有一种很好的方法来插入字符串,如 ES5、Ruby 和 Python 的字符串。

class Client(val firstName: String, val lastName: String) {
    val fullName = "$firstName $lastName"
}