在 Java 上,我知道接下来的事情就可以了:
String test="aaa";
System.out.println(String.format(test,"asd"));
(打印“aaa”)
但是,我希望能够处理相反的事情,例如:
String test="aaa%sbbb";
System.out.println(String.format(test));
(这会产生异常 java.util.MissingFormatArgumentException )
我希望使其尽可能通用,无论有多少说明符/参数,如果没有足够的值,只需忽略它们(从有问题的位置跳过所有说明符)并编写其余部分字符串(例如,在我所展示的情况下,它将写成“aaabbb”)。
是否可以开箱即用,或者我应该编写一个函数来实现它?
最佳答案
好吧,我想我已经有了一个可行的解决方案,而且我还认为它支持 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 和一个字符串,但它可以工作。
关于java - 当没有足够的参数时,如何克服 String.format 的 MissingFormatArgumentException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16502603/