好吧,我想我已經得到了有效的解決方案,並且我也認爲它支持的String.format支持一切:
public static String formatString(final String stringToFormat,final Object... args)
{
if(stringToFormat==null||stringToFormat.length()==0)
return stringToFormat;
int specifiersCount=0;
final int argsCount=args==null ? 0 : args.length;
final StringBuilder sb=new StringBuilder(stringToFormat.length());
for(int i=0;i<stringToFormat.length();++i)
{
char c=stringToFormat.charAt(i);
if(c!='%')
sb.append(c);
else
{
final char nextChar=stringToFormat.charAt(i+1);
if(nextChar=='%'||nextChar=='n')
{
++i;
sb.append(c);
sb.append(nextChar);
continue;
}
// found a specifier
++specifiersCount;
if(specifiersCount<=argsCount)
sb.append(c);
else while(true)
{
++i;
c=stringToFormat.charAt(i);
// find the end of the converter, to ignore it all
if(c=='t'||c=='T')
{
// time prefix and then a character, so skip it
++i;
break;
}
if(c>='a'&&c<='z'||c>='A'&&c<='Z')
break;
}
}
}
return String.format(sb.toString(),args);
}
和測試,只是爲了顯示它的工作原理:
System.out.println(formatString("aaa%sbbb"));
System.out.println(formatString("%da%sb%fc%tBd%-15se%16sf%10.2fg"));
不幸的是,它創建了一個新的stringBuilder和一個字符串的方式,但它的工作原理。
只是說明:有一個'System.out.format()'方法。 – Keppil 2013-05-11 23:18:28
是的,我忘了它,但它只是一個樣本。我不需要在我使用它的真實場景中寫入控制檯。 – 2013-05-12 07:39:45