Question

Wondering if it is possible to combine both a single string and varargs string in a String.format(), like this:

String strFormat(String template, String str, String... moreStrs) {    
    return String.format(template, str, moreStrs);
}

If I call the above like this:

strFormat("%s/%s/%s", "hello", "world", "goodbye");

I get java.util.MissingFormatArgumentException: Format specifier 's'

This works:

String strFormat(String template, String... moreStrs) {    
    return String.format(template, moreStrs);
}

As well as this works:

String strFormat(String template, String str1, String str2) {    
    return String.format(template, str1, str2);
}

Is it possible to get this to work?

String strFormat(String template, String str, String... moreStrs) {    
    return String.format(template, str, moreStrs);
}

Thanks!

Was it helpful?

Solution

You can do it like this:

String strFormat(String template, String str, String... moreStrs)
{
    String[] args = new String[moreStrs.length + 1];

    // fill the array 'args'
    System.arraycopy(moreStrs, 0, args, 0, moreStrs.length);
    args[moreStrs.length] = str;

    return String.format(template, args);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top