Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combined usage of String and Varargs in String.format()

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!

like image 634
Bala Avatar asked Jul 29 '13 22:07

Bala


1 Answers

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);
}
like image 163
Eng.Fouad Avatar answered Sep 28 '22 01:09

Eng.Fouad