簡體   English   中英

如何從Java中的String替換特定單詞

[英]How to replace a specific word from String in Java

如何從字符串“恭喜{{customer}}”中替換“ {{customer}}”,並用“ xyz”代替。

在此先感謝您的建議。

像這樣?

 String string = "Congrats {{customer}}";
 String newValue = string.replace("{{customer}}", "xyz");

  // 'string' remains the same..but 'newValue' has the replacement.
 System.out.println(newValue);

使用String對象上的replace方法來執行此操作。 由於String是不可變的,它將返回帶有替換文本的新對象實例。 例:

String myString = "Congrats {{customer}}";
myString = myString.replace("{{customer}}","John");
System.out.println(myString);

輸出:

Congrats John

有關更多有用的實用程序方法,請參見String javadoc

看起來像胡須模板。

參見https://github.com/spullara/mustache.java

通常,在您的情況下:

HashMap<String, Object> scopes = new HashMap<String, Object>();
scopes.put("customer", "xyz");

Writer writer = new OutputStreamWriter(System.out);
MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile(new StringReader("Congrats {{customer}}, you become the potential winner of auction"), "example");
mustache.execute(writer, scopes);
writer.flush();

使用資源,可以使用如下方法:

String customer = "Joe Doe";
String textHello;

textHello = String.format(getString(R.string.hello_customer), customer);

其中hello_customer是您的字符串resorce strings.xml。

strings.xml部分應如下所示:

<string name="hello_customer">Congrats %1$s, you become the potential winner of auction with \"xyz\".</string>

暫無
暫無

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

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