繁体   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