Java GWT 中的字符串格式化程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3126232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String Formatter in GWT
提问by unj2
How do I format my string in GWT?
如何在 GWT 中格式化我的字符串?
I made a method
我做了一个方法
Formatter format = new Formatter();
int matches = 0;
Formatter formattedString = format.format("%d numbers(s, args) in correct position", matches);
return formattedString.toString();
But it complains by saying
但它抱怨说
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?
Isn't Formatter included?
不包括格式化程序吗?
采纳答案by Pace
回答by yegor256
A very simple replacement for String.format() in GWT 2.1+:
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();
}
回答by Antonio
As an alternative you can use class NumberFormat:
作为替代方案,您可以使用类NumberFormat:
NumberFormat fmt = NumberFormat.getDecimalFormat();
double value = 12345.6789;
String formatted = fmt.format(value);
// Prints 1,2345.6789 in the default locale
回答by bodrin
another very very simple replacement for java.text.MessageFormat.format() :
另一个非常简单的 java.text.MessageFormat.format() 替代品:
public static String format(final String format, final Object... args) {
StringBuilder sb = new StringBuilder();
int cur = 0;
int len = format.length();
while (cur < len) {
int fi = format.indexOf('{', cur);
if (fi != -1) {
sb.append(format.substring(cur, fi));
int si = format.indexOf('}', fi);
if (si != -1) {
String nStr = format.substring(fi + 1, si);
int i = Integer.parseInt(nStr);
sb.append(args[i]);
cur = si + 1;
} else {
sb.append(format.substring(fi));
break;
}
} else {
sb.append(format.substring(cur, len));
break;
}
}
return sb.toString();
}
回答by ka2
Or even simpler, not using RegExp, and using only Strings:
或者更简单,不使用 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();
}
回答by Daniel Harvey
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();
}
回答by Joseph Lust
See the official pageon GWT date and number formatting.
请参阅有关 GWT 日期和数字格式的官方页面。
They suggest the following:
他们建议如下:
myNum decimal = 33.23232;
myString = NumberFormat.getFormat("#.00").format(decimal);
It is best to use their supported, optimized methods, than to cook up your own non-optimal method. Their compiler will be optimizing them all to nearly the same thing anyway in the end.
最好使用他们支持的优化方法,而不是编写自己的非最佳方法。无论如何,他们的编译器最终都会将它们优化为几乎相同的东西。
回答by Gio
Maybe the easiest way to do something like String.format, can be do it with a String.replace, for instance;
例如,执行 String.format 之类的最简单方法可能是使用 String.replace 来实现;
instead of do String.format("Hello %s", "Daniel");
==> "Hello %s".replace("%s", "Daniel")
,
而不是做String.format("Hello %s", "Daniel");
==> "Hello %s".replace("%s", "Daniel")
,
both give us the same result, but just the second way works in GWT client side
两者都给我们相同的结果,但只有第二种方式在 GWT 客户端工作
回答by Gio
I'm not keen on abusing string manipulation for doing regexps' job, but, based on bodrin's solution, you can code:
我不热衷于滥用字符串操作来完成正则表达式的工作,但是,基于 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;
}
回答by Mikha
Another suggestion which makes use of JSNIand a nice JavaScript format function from another post:
另一个使用JSNI和来自另一篇文章的不错的 JavaScript 格式函数的建议:
import com.google.gwt.core.client.JsArrayString;
public abstract class StringFormatter {
public static String format(final String format, final Object... args) {
if (null == args || 0 == args.length)
return format;
JsArrayString array = newArray();
for (Object arg : args) {
array.push(String.valueOf(arg)); // TODO: smarter conversion?
}
return nativeFormat(format, array);
}
private static native JsArrayString newArray()/*-{
return [];
}-*/;
private static native String nativeFormat(final String format, final JsArrayString args)/*-{
return format.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined' ? args[number] : match;
});
}-*/;
}
One can then make a call like this:
然后可以像这样拨打电话:
StringFormatter.format("Greetings {0}, it's {1} o'clock, which is a {2} statement", "Master", 8, false);
...with the result being
...结果是
Greetings Master, it's 8 o'clock, which is a false statement
师父您好,现在是八点,这是一个错误的说法
There is a potential to improve further at the TODOcomment, e.g. utilise NumberFormat. Suggestions are welcome.
TODO注释有进一步改进的潜力,例如使用 NumberFormat。欢迎提出建议。