[英]How to replace a specific word from String in Java
How to replace "{{customer}}" from this string "Congrats {{customer}}, you become the potential winner of auction" with "xyz". 如何从字符串“恭喜{{customer}}”中替换“ {{customer}}”,并用“ xyz”代替。
Thanks in advance, Suggestion appreciated. 在此先感谢您的建议。
like this? 像这样?
String string = "Congrats {{customer}}";
String newValue = string.replace("{{customer}}", "xyz");
// 'string' remains the same..but 'newValue' has the replacement.
System.out.println(newValue);
Use the replace
method on the String
object to do this. 使用
String
对象上的replace
方法来执行此操作。 Since String
is immutable it will return a new object instance with the replaced text. 由于
String
是不可变的,它将返回带有替换文本的新对象实例。 Example: 例:
String myString = "Congrats {{customer}}";
myString = myString.replace("{{customer}}","John");
System.out.println(myString);
Output: 输出:
Congrats John
See also the String javadoc for many more useful utility methods. 有关更多有用的实用程序方法,请参见String javadoc 。
That looks like a mustache template. 看起来像胡须模板。
See https://github.com/spullara/mustache.java 参见https://github.com/spullara/mustache.java
Typically, in your case: 通常,在您的情况下:
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();
Using resources, you can use method like this: 使用资源,可以使用如下方法:
String customer = "Joe Doe";
String textHello;
textHello = String.format(getString(R.string.hello_customer), customer);
where hello_customer
is your string resorce strings.xml. 其中
hello_customer
是您的字符串resorce strings.xml。
strings.xml part should look like this: 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.