簡體   English   中英

用字符串替換大括號的標准方法是什么?

[英]What is the standard way to replace curly brackets with a string?

用字符串替換大括號的標准方法是什么?

我有一個模板字符串,如:

String template = "Please deploy the {0} project to the {1} server.";
String var0 = "cool new";
String var1 = "test";

有沒有一種方法可以做到這一點? 也許國際化會做什么?

String newV = replaceVar(template, new Object[]{var0,var1});

謝謝,

雖然有多種可能的方法可以做到這一點,但對我來說這看起來適合MessageFormat 1 喜歡,

String template = "Please deploy the {0} project to the {1} server.";
String var0 = "cool new";
String var1 = "test";
MessageFormat mf = new MessageFormat(template, Locale.ENGLISH);
System.out.println(mf.format(new Object[] { var0, var1 }));

哪個輸出

Please deploy the cool new project to the test server.

1 JEP 草案:字符串模板(預覽版)可能會更好。 在將來。

您可以使用 String.format() function,它采用兩個參數:要格式化的字符串和 arguments。 您應該將“%s”放在將被 arguments 替換的空格上。 注意:您應該將 %d 用於整數,將 %f 用於浮點值,將 %s 用於字符串。

String s = String.format("Please deploy the %s project to the %s server.", "cool new", "test");
    System.out.println(s);

這將 output:請將酷炫的新項目部署到測試服務器。

PS:Arguments按順序更換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM