NeverSleeps
NeverSleeps

Reputation: 1902

Using a Variable Length Argument List for String.format()

I get a string-template and a variable-length argument list. I need I need to insert arguments into the template and send the result.

For instance:

template: "%1s test %2s test %1s"

args: "CAT", "DOG"

Result: "CAT test DOG test CAT"

I tried to do it like this. But I got an error, because in fact, I'm trying to execute the string String.format("%1s test %2s test %1s", "value") which is really wrong.


    public static void main(String[] args) {
        getStringFromTemplate("%1s test %2s test %1s", "CAT", "DOG");
    }

    public void getStringFromTemplate(String template, String... args){
        ArrayList<String> states = new ArrayList<>();
        Collections.addAll(states, args);
        String s;
        Iterator<String> iter = states.iterator();
        while(iter.hasNext()){
            s = String.format("%1s test %2s test %1s", iter.next());
        }
        rerurn s;
    }

Upvotes: 1

Views: 1201

Answers (2)

ginkul
ginkul

Reputation: 1066

String.format takes as the second argument varargs, so you could just rewrite your code like this:

public static String getStringFromTemplate(String template, String ...args) {
    return String.format(template, args);
}

Also, if you want to use one parameter many times, you should change your template String:

template = "%1$s test %2$s test %1$s";

You can find understandable tutorial here.

Upvotes: 3

Aaron
Aaron

Reputation: 24812

I believe you're looking for this :

public String getStringFromTemplate(String template, String... args){
    for (int i=0; i<args.length; i++) {
        String placeholder = "%" + (i+1) + "s";
        String actualValue=args[i];
        template = template.replaceAll(placeholder, actualValue);
    }
    return template;
}

This code iterates over your arguments, derives a placeholder from their index in the args array and replace all occurences of this placeholder by the actual value of the argument in the template string.

You can try it here

Upvotes: 0

Related Questions