如何在Java中替换String中的特定单词

时间:2014-11-11 15:55:28

标签: java android

如何更换" {{customer}}"从这个字符串"恭喜{{customer}},你成为拍卖的潜在赢家"与" xyz"。

提前致谢, 建议表示赞赏。

4 个答案:

答案 0 :(得分:3)

像这样?

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

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

答案 1 :(得分:1)

使用replace对象上的String方法执行此操作。由于String是不可变的,因此它将返回带有替换文本的新对象实例。例如:

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

输出:

Congrats John

有关更多有用的实用程序方法,另请参阅String javadoc

答案 2 :(得分:0)

这看起来像一个小胡子模板。

请参阅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();

答案 3 :(得分:0)

使用资源,您可以使用以下方法:

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>