Reputation: 27
I receive a string of form similar to "%value1% - %value2% interval" and I have two integers let's say v1, and v2, and the two values have to substitute the corresponding fields and the String to look in the end "v1 - v2 interval" I tried the following:
StringBuilder valueBuilder = new StringBuilder();
valueBuilder.append("%value1% - %value2% interval");
ageBuilder.append(String.format(Locale.getDefault(), "%1$d - %2$d interval", value1, value2))
I cannot modify the initial "%value1% - %value2% interval" part of the string! I can only substitute %value1% and %value2% from it that I receive like that
Do you have any suggestions? Thanks!
Upvotes: 0
Views: 806
Reputation: 2197
using the replace()
method:
StringBuilder valueBuilder = new StringBuilder();
int v1 = 10;
int v2 = 20;
valueBuilder.append(
"%value1% - %value2% interval"
.replace("%value1%", String.valueOf(v1))
.replace("%value2%", String.valueOf(v2))
);
System.out.println(valueBuilder);
output:
10 - 20 interval
Upvotes: 0
Reputation: 270
You can to use specifiers to insert the variables into the string.
int value1 = 1;
int value2 = 2;
StringBuilder valueBuilder = new StringBuilder();
valueBuilder.append(" ");
ageBuilder.append(String.format(Locale.getDefault(), "v%d - v%d interval", value1, value2))
The %d
will be replaced with the value1
and value2
.
String.format()
v1 - v2 interval
See more here: https://dzone.com/articles/java-string-format-examples
Upvotes: 1
Reputation: 107
hope this helps
int value1 = 11, value2 =12;
String formattedString = String.format("%s %d - %d", Locale.getDefault(), value1, value2);
System.out.println(formattedString);
output is
en_US 11 - 12
Upvotes: 0