2013-07-29 17 views
5

Zastanawiasz się, czy możliwe jest, aby łączyć zarówno pojedynczy łańcuch i varargs ciąg w string.Format() w następujący sposób:Combined wykorzystanie ciąg i varargs w string.Format()

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

Jeśli zadzwonię wyżej tak:

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

dostaję java.util.MissingFormatArgumentException: Format specifier 's'

to działa:

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

Podobnie jak to działa:

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

Czy to możliwe, aby to działało?

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

Dzięki!

+0

Dlaczego chcesz się wyrwać jeden 'str' od reszty strun? Czy próbujesz wymagać przekazania co najmniej jednego 'str'? – rgettman

+0

Nie, to nie jest sposób definiowania interfejsu API. Dlaczego chcesz to zrobić? –

+0

@rgettman i do Jima Garrisona: Byłam ciekawa, czy to zadziała, i chciałabym się dowiedzieć, czy to nie pomoże. – Bala

Odpowiedz

5

Można to zrobić tak:

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); 
} 
+0

Dzięki, to zadziałało. – Bala

+1

OMFG. Jest to nawet gorsze od argumentów JavaScript '. – Tino