Java使用占位符生成字符串

ndr*_*zza 38 java string

我正在寻找能够实现以下目标的东西:

String s = "hello {}!";
s = generate(s, new Object[]{ "world" });
assertEquals(s, "hello world!"); // should be true
Run Code Online (Sandbox Code Playgroud)

我可以自己编写,但在我看来,我曾经看过一个库,它曾经做过这个,可能是slf4j记录器,但我不想写日志消息.我只是想生成字符串.

你知道一个图书馆吗?

Grz*_*Żur 55

String.format方法.

String s = "hello %s!";
s = String.format(s, "world");
assertEquals(s, "hello world!"); // should be true
Run Code Online (Sandbox Code Playgroud)

  • @Carlos.V 使用 `String.format("Hello %swelcome to %s!", "Carlos.V", "JAVA");` 将打印 `Hello Carlos.V", "JAVA");` 欢迎使用 JAVA!`,您可以使用尽可能多的 %s。:) (2认同)

Jus*_*tas 28

StrSubstitutor 来自Apache Commons Lang可用于使用命名占位符进行字符串格式化:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.1</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

https://commons.apache.org/proper/commons-lang/javadocs/api-3.4/org/apache/commons/lang3/text/StrSubstitutor.html:

用值替换字符串中的变量.

该类接受一段文本并替换其中的所有变量.变量的默认定义是$ {variableName}.可以通过构造函数和set方法更改前缀和后缀.

变量值通常从映射中解析,但也可以从系统属性中解析,或者通过提供自定义变量解析器来解析.

例:

String template = "Hi ${name}! Your number is ${number}";

Map<String, String> data = new HashMap<String, String>();
data.put("name", "John");
data.put("number", "1");

String formattedString = StrSubstitutor.replace(template, data);
Run Code Online (Sandbox Code Playgroud)

  • 不推荐使用StrSubstitutor,请参阅[此SO帖子以获取解决方法。](/sf/ask/983130081/) (2认同)

Abh*_*ekB 19

这可以在不使用库的情况下在一行中完成。请检查java.text.MessageFormat类。

例子

String stringWithPlaceHolder = "test String with placeholders {0} {1} {2} {3}";
String formattedStrin = java.text.MessageFormat.format(stringWithPlaceHolder, "place-holder-1", "place-holder-2", "place-holder-3", "place-holder-4");
Run Code Online (Sandbox Code Playgroud)

输出将是

test String with placeholders place-holder-1 place-holder-2 place-holder-3 place-holder-4
Run Code Online (Sandbox Code Playgroud)

  • 这是添加本地化时的最佳解决方案,因为不同语言的占位符顺序会发生变化。 (2认同)

fge*_*fge 8

有两种解决方案:

Formatter虽然它接管了printf()40年,但它是最新的......

您目前定义的占位符是MessageFormat可以使用的,但为什么要使用古董技术?;)使用Formatter.

有更多的理由使用Formatter你不需要逃避单引号!MessageFormat要求你这样做.另外,Formatter具有通过快捷方式String.format()到生成的字符串,和PrintWriter■找.printf()(包括System.outSystem.err这两者都是PrintWriterš默认情况下)


Lau*_*ntG 7

如果您可以更改占位符的格式,则可以使用String.format().如果没有,您也可以将其替换为预处理.

String.format("hello %s!", "world");
Run Code Online (Sandbox Code Playgroud)

有关此其他主题的更多信息.


das*_*ght 6

如果您可以容忍不同类型的占位符(即%s代替{}),您可以使用String.format以下方法:

String s = "hello %s!";
s = String.format(s, "world" );
assertEquals(s, "hello world!"); // true
Run Code Online (Sandbox Code Playgroud)


cod*_*box 5

你不需要图书馆; 如果您使用的是最新版本的Java,请查看String.format:

String.format("Hello %s!", "world");
Run Code Online (Sandbox Code Playgroud)