How do I format my string in GWT?
I made a method
Formatter format = new Formatter();
int matches = 0;
Formatter formattedString = format.forma
This one is pretty fast and ignores bad curly-delimited values:
public static String format(final String format, final Object... args)
{
if (format == null || format.isEmpty()) return "";
// Approximate the result length: format string + 16 character args
StringBuilder sb = new StringBuilder(format.length() + (args.length*16));
final char openDelim = '{';
final char closeDelim = '}';
int cur = 0;
int len = format.length();
int open;
int close;
while (cur < len)
{
switch (open = format.indexOf(openDelim, cur))
{
case -1:
return sb.append(format.substring(cur, len)).toString();
default:
sb.append(format.substring(cur, open));
switch (close = format.indexOf(closeDelim, open))
{
case -1:
return sb.append(format.substring(open)).toString();
default:
String nStr = format.substring(open + 1, close);
try
{
// Append the corresponding argument value
sb.append(args[Integer.parseInt(nStr)]);
}
catch (Exception e)
{
// Append the curlies and the original delimited value
sb.append(openDelim).append(nStr).append(closeDelim);
}
cur = close + 1;
}
}
}
return sb.toString();
}