2

How to replace "{{customer}}" from this string "Congrats {{customer}}, you become the potential winner of auction" with "xyz".

Thanks in advance, Suggestion appreciated.

4 Answers 4

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

what kind of error do you get? Note that the string is only replaced on the 'newValue' variable..not on the 'string' variable itself.
1

Use the replace method on the String object to do this. Since String is immutable it will return a new object instance with the replaced text. 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.

Comments

0

That looks like a mustache template.

See 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();

Comments

0

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.

strings.xml part should look like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.