Java GWT中的字符串格式化程序
如何在GWT中格式化字符串 我制定了一个方法Java GWT中的字符串格式化程序,java,gwt,Java,Gwt,如何在GWT中格式化字符串 我制定了一个方法 Formatter format = new Formatter(); int matches = 0; Formatter formattedString = format.format("%d numbers(s, args) in correct position", matches); return formattedString.toString(); 但它抱怨说 Validating newly compil
Formatter format = new Formatter();
int matches = 0;
Formatter formattedString = format.format("%d numbers(s, args) in correct position", matches);
return formattedString.toString();
但它抱怨说
Validating newly compiled units
[ERROR] Errors in 'file:/C:/Documents%20and%20Settings/kkshetri/workspace/MasterMind/MasterMind/src/com/kunjan/MasterMind/client/MasterMind.java'
[ERROR] Line 84: No source code is available for type java.util.Formatter; did you forget to inherit a required module?
不包括格式化程序吗?更新:在进一步查看此答案之前,请参阅(并投票)约瑟夫·卢斯特在下面的帖子
根据,似乎未包括格式化程序。但是,他们提出了一些替代方案。GWT 2.1+中String.format()的一个非常简单的替代品:
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.regexp.shared.SplitResult;
public static String format(final String format, final Object... args) {
final RegExp regex = RegExp.compile("%[a-z]");
final SplitResult split = regex.split(format);
final StringBuffer msg = new StringBuffer();
for (int pos = 0; pos < split.length() - 1; ++pos) {
msg.append(split.get(pos));
msg.append(args[pos].toString());
}
msg.append(split.get(split.length() - 1));
return msg.toString();
}
import com.google.gwt.regexp.shared.regexp;
导入com.google.gwt.regexp.shared.SplitResult;
公共静态字符串格式(最终字符串格式、最终对象…args){
final RegExp regex=RegExp.compile(“%[a-z]”);
最终SplitResult split=regex.split(格式);
final StringBuffer msg=新StringBuffer();
对于(int pos=0;pos
作为替代,您可以使用类:
java.text.MessageFormat.format()的另一个非常简单的替代品:
公共静态字符串格式(最终字符串格式、最终对象…args){
StringBuilder sb=新的StringBuilder();
int cur=0;
int len=format.length();
while(cur
甚至更简单,不使用RegExp,只使用字符串:
public static String format(final String format, final String... args) {
String[] split = format.split("%s");
final StringBuffer msg = new StringBuffer();
for (int pos = 0; pos < split.length - 1; pos += 1) {
msg.append(split[pos]);
msg.append(args[pos]);
}
msg.append(split[split.length - 1]);
return msg.toString();
}
公共静态字符串格式(最终字符串格式、最终字符串…args){
String[]split=format.split(“%s”);
final StringBuffer msg=新StringBuffer();
对于(int pos=0;pos
此选项速度非常快,并忽略错误的卷曲分隔值:
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();
}
公共静态字符串格式(最终字符串格式、最终对象…args)
{
if(format==null | | format.isEmpty())返回“”;
//近似结果长度:格式字符串+16个字符的参数
StringBuilder sb=新的StringBuilder(format.length()+(args.length*16));
最终字符openDelim='{';
最终字符closeDelim='}';
int cur=0;
int len=format.length();
int-open;
int-close;
while(cur
请参阅有关GWT日期和编号格式的说明
他们建议如下:
myNum decimal = 33.23232;
myString = NumberFormat.getFormat("#.00").format(decimal);
最好使用他们支持的、优化的方法,而不是自己炮制非优化的方法。他们的编译器最终将对它们进行优化,使其几乎达到相同的效果。也许像String.format这样的操作最简单的方法就是使用String.replace 而不是do
String.format(“Hello%s”,“Daniel”)代码>==>“你好%s”。替换(“%s”,“Daniel”)
两者都给出了相同的结果,但第二种方法在GWT客户端工作我不喜欢滥用字符串操作来完成regexp的工作,但是,根据bodrin的解决方案,您可以编写:
public static String format (String pattern, final Object ... args) {
for (Object arg : args) {
String part1 = pattern.substring(0,pattern.indexOf('{'));
String part2 = pattern.substring(pattern.indexOf('}') + 1);
pattern = part1 + arg + part2;
}
return pattern;
}
另一个建议是使用和一个漂亮的JavaScript格式函数,来自:
然后你可以打这样的电话:
StringFormatter.format("Greetings {0}, it's {1} o'clock, which is a {2} statement", "Master", 8, false);
…结果是
大师您好,现在是8点,这是一个错误的说法
在待办事项评论中有进一步改进的潜力,例如使用NumberFormat。欢迎提出建议。如上所述,有用于数字和日期的GWT格式化程序:NumberFormat
和DateTimeFormat
。
尽管如此,我仍然需要一个解决方案来解决众所周知的String.format(…)
案例。
我最终得到了这个解决方案,我不知道它的性能是否有问题,但它在视觉上是干净的。我很高兴听到任何关于它或其他解决方案的评论
我的字符串格式化程序:
public class Strings {
public static String format(final String format, final Object... args) {
String retVal = format;
for (final Object current : args) {
retVal = retVal.replaceFirst("[%][s]", current.toString());
}
return retVal;
}
}
如果你想重复使用它,最重要的是:
public class StringsTest {
@Test
public final void testFormat() {
this.assertFormat("Some test here %s.", 54);
this.assertFormat("Some test here %s and there %s, and test [%s]. sfsfs !!!", 54, 59, "HAHA");
}
private void assertFormat(final String format, final Object... args) {
Assert.assertEquals("Formatting is not working", String.format(format, args), Strings.format(format, args));
}
}
Daniels解决方案的扩展:还支持在无法解析数字时使用“and throws”进行转义(就像JVM版本那样):
逃逸测试:
// Escaping with no replacement
assertFormat("It's the world", "Its the world");
assertFormat("It''s the world", "It's the world");
assertFormat("Open ' and now a second ' (closes)", "Open and now a second (closes)");
assertFormat("It'''s the world", "It's the world");
assertFormat("'{0}' {1} {2}", "{0} one two", "zero", "one", "two");
// Stays escaped (if end escape is missing)
assertFormat("'{0} {1} {2}", "{0} {1} {2}", "zero", "one", "two");
assertFormat("'{0} {1}' {2}", "{0} {1} two", "zero", "one", "two");
// No matter where we escape, stays escaped
assertFormat("It's a {0} world", "Its a {0} world", "blue");
// But we can end escape everywhere
assertFormat("It's a {0} world, but not '{1}",
"Its a {0} world, but not always", "blue", "always");
// I think we want this
assertFormat("It''s a {0} world, but not {1}",
"It's a blue world, but not always", "blue", "always");
// Triple
assertFormat("' '' '", " ' ");
// From oracle docs
assertFormat("'{''}'", "{'}");
// Missing argument (just stays 0)
assertFormat("begin {0} end", "begin {0} end");
// Throws
try {
assertFormat("begin {not_a_number} end", "begin {not_a_number} end");
throw new AssertionError("Should not get here");
} catch (IllegalArgumentException iae) {
// OK
}
您是否在MasterMind.java文件中导入了java.util.Formatter?值得一提的还有NumberFormat
和DateTimeFormat
。我的IDE抱怨说,NumberFormat在JRE仿真中不存在,但它似乎可以工作……这对我来说是真实的、合法的。[参考@Joseph Lust答案b
public class Strings {
public static String format(final String format, final Object... args) {
String retVal = format;
for (final Object current : args) {
retVal = retVal.replaceFirst("[%][s]", current.toString());
}
return retVal;
}
}
public class StringsTest {
@Test
public final void testFormat() {
this.assertFormat("Some test here %s.", 54);
this.assertFormat("Some test here %s and there %s, and test [%s]. sfsfs !!!", 54, 59, "HAHA");
}
private void assertFormat(final String format, final Object... args) {
Assert.assertEquals("Formatting is not working", String.format(format, args), Strings.format(format, args));
}
}
private static final char OPEN = '{';
private static final char CLOSE = '}';
private static final char ESCAPE = '\'';
@Override
public String format(String pattern, Object... arguments) {
if (pattern == null || pattern.isEmpty())
return "";
// Approximate the result length: format string + 16 character args
StringBuilder sb = new StringBuilder(pattern.length() + (arguments.length * 16));
int cur = 0;
int len = pattern.length();
// if escaped, then its >= 0
int escapedAtIndex = -1;
while (cur < len) {
char currentChar = pattern.charAt(cur);
switch (currentChar) {
case OPEN:
if (escapedAtIndex >= 0) {
// currently escaped
sb.append(currentChar);
} else {
// find close
int close = pattern.indexOf(CLOSE, cur + 1);
switch (close) {
case -1:
// Missing close. Actually an error. But just ignore
sb.append(currentChar);
break;
default:
// Ok, we have a close
final String nStr = pattern.substring(cur + 1, close);
try {
// Append the corresponding argument value
sb.append(arguments[Integer.parseInt(nStr)]);
} catch (Exception e) {
if (e instanceof NumberFormatException) {
throw new IllegalArgumentException(nStr +
" is not a number.");
}
// Append the curlies and the original delimited value
sb.append(OPEN).append(nStr).append(CLOSE);
}
// Continue after the close
cur = close;
break;
}
}
cur++;
break;
case ESCAPE:
// Special case: two '' are just converted to '
boolean nextIsEscapeToo = (cur + 1 < len) && pattern.charAt(cur + 1) == ESCAPE;
if (nextIsEscapeToo) {
sb.append(ESCAPE);
cur = cur + 2;
} else {
if (escapedAtIndex >= 0) {
// Escape end.
escapedAtIndex = -1;
} else {
// Escape start.
escapedAtIndex = cur;
}
cur++;
}
break;
default:
// 90% case: Nothing special, just a normal character
sb.append(currentChar);
cur++;
break;
}
}
return sb.toString();
}
// Replace: 0 items
assertFormat("Nothing to replace", "Nothing to replace");
// Replace: 1 item
assertFormat("{0} apples", "15 apples", 15);
assertFormat("number of apples: {0}", "number of apples: zero", "zero");
assertFormat("you ate {0} apples", "you ate some apples", "some");
// Replace 2 items
assertFormat("{1} text {0}", "second text first", "first", "second");
assertFormat("X {1} text {0}", "X second text first", "first", "second");
assertFormat("{0} text {1} X", "first text second X", "first", "second");
// Escaping with no replacement
assertFormat("It's the world", "Its the world");
assertFormat("It''s the world", "It's the world");
assertFormat("Open ' and now a second ' (closes)", "Open and now a second (closes)");
assertFormat("It'''s the world", "It's the world");
assertFormat("'{0}' {1} {2}", "{0} one two", "zero", "one", "two");
// Stays escaped (if end escape is missing)
assertFormat("'{0} {1} {2}", "{0} {1} {2}", "zero", "one", "two");
assertFormat("'{0} {1}' {2}", "{0} {1} two", "zero", "one", "two");
// No matter where we escape, stays escaped
assertFormat("It's a {0} world", "Its a {0} world", "blue");
// But we can end escape everywhere
assertFormat("It's a {0} world, but not '{1}",
"Its a {0} world, but not always", "blue", "always");
// I think we want this
assertFormat("It''s a {0} world, but not {1}",
"It's a blue world, but not always", "blue", "always");
// Triple
assertFormat("' '' '", " ' ");
// From oracle docs
assertFormat("'{''}'", "{'}");
// Missing argument (just stays 0)
assertFormat("begin {0} end", "begin {0} end");
// Throws
try {
assertFormat("begin {not_a_number} end", "begin {not_a_number} end");
throw new AssertionError("Should not get here");
} catch (IllegalArgumentException iae) {
// OK
}