String variable interpolation Java [duplicate]

血红的双手。 提交于 2019-11-26 12:03:02

问题


This question already has an answer here:

  • How to format strings in Java 6 answers

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

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:

    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));

回答1:


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

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

See Formatter for details.




回答2:


Note that there is no variable interpolation in Java. Variable interpolation is variable substitution with its value inside a string. An example in 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.

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

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.

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

Edit As 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:

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.




回答3:


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

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.



回答4:


String.format() to the rescue!!




回答5:


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.

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


来源:https://stackoverflow.com/questions/6389827/string-variable-interpolation-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!