Search code examples
javastringformatstring-formattingstringbuilder

How to properly format a string with 2 integers in java


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!


Solution

  • 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