Combined usage of String and Varargs in String.format()
Asked Answered
U

1

9

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!

Udell answered 29/7, 2013 at 22:57 Comment(3)
Why do you want to break out one str from the rest of the strings? Are you attempting to require at least one str to be passed?Child
No, that's not how the API is defined. Why do you want to do that?Apologete
@Child and to Jim Garrison: Was just curious to see if it would work and wanted to know the work-around if it did not.Udell
R
9

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);
}
Redingote answered 29/7, 2013 at 23:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.