如何在 Java 中格式化字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6431933/
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
How to format strings in Java
提问by katit
Primitive question, but how do I format strings like this:
原始问题,但我如何格式化这样的字符串:
"Step {1} of {2}"
“{2} 的第 {1} 步”
by substituting variables using Java? In C# it's easy.
通过使用Java替换变量?在 C# 中很容易。
采纳答案by ataylor
In addition to String.format, also take a look java.text.MessageFormat
. The format less terse and a bit closer to the C# example you've provided and you can use it for parsing as well.
除了String.format,也看看java.text.MessageFormat
。格式更简洁,更接近您提供的 C# 示例,您也可以将其用于解析。
For example:
例如:
int someNumber = 42;
String someString = "foobar";
Object[] args = {new Long(someNumber), someString};
MessageFormat fmt = new MessageFormat("String is \"{1}\", number is {0}.");
System.out.println(fmt.format(args));
A nicer example takes advantage of the varargs and autoboxing improvements in Java 1.5 and turns the above into a one-liner:
一个更好的例子利用了 Java 1.5 中的可变参数和自动装箱改进,并将上面的内容变成了一个单行:
MessageFormat.format("String is \"{1}\", number is {0}.", 42, "foobar");
MessageFormat
is a little bit nicer for doing i18nized plurals with the choice modifier. To specify a message that correctly uses the singular form when a variable is 1 and plural otherwise, you can do something like this:
MessageFormat
用选择修饰符做 i18nized 复数会更好一点。要指定在变量为 1 时正确使用单数形式的消息,否则可以执行以下操作:
String formatString = "there were {0} {0,choice,0#objects|1#object|1<objects}";
MessageFormat fmt = new MessageFormat(formatString);
fmt.format(new Object[] { new Long(numberOfObjects) });
回答by Martin T?rnwall
Take a look at String.format. Note, however, that it takes format specifiers similar to those of C's printf family of functions -- for example:
看看String.format。但是请注意,它采用类似于 C 的 printf 系列函数的格式说明符——例如:
String.format("Hello %s, %d", "world", 42);
Would return "Hello world, 42". You may find thishelpful when learning about the format specifiers. Andy Thomas-Cramer was kind enough to leave thislink in a comment below, which appears to point to the official spec. The most commonly used ones are:
将返回“Hello world, 42”。在了解格式说明符时,您可能会发现这很有帮助。安迪·托马斯-克莱默 (Andy Thomas-Cramer)在下面的评论中留下了这个链接,这似乎指向了官方规范。最常用的有:
- %s - insert a string
- %d - insert a signed integer (decimal)
- %f - insert a real number, standard notation
- %s - 插入一个字符串
- %d - 插入一个有符号整数(十进制)
- %f - 插入一个实数,标准符号
This is radically different from C#, which uses positional references with an optional format specifier. That means that you can't do things like:
这与 C# 完全不同,C# 使用带有可选格式说明符的位置引用。这意味着您不能执行以下操作:
String.format("The {0} is repeated again: {0}", "word");
... without actually repeating the parameter passed to printf/format.(see The Scrum Meister's comment below)
...实际上没有重复传递给 printf/format 的参数。(请参阅下面的 Scrum 大师的评论)
If you just want to print the result directly, you may find System.out.printf (PrintStream.printf) to your liking.
如果您只想直接打印结果,您可以根据自己的喜好找到 System.out.printf ( PrintStream.printf)。
回答by Ryan Amos
If you choose not to use String.format, the other option is the + binary operator
如果您选择不使用 String.format,另一个选项是 + 二元运算符
String str = "Step " + a + " of " + b;
This is the equivalent of
这相当于
new StringBuilder("Step ").append(String.valueOf(1)).append(" of ").append(String.valueOf(2));
new StringBuilder("Step ").append(String.valueOf(1)).append(" of ").append(String.valueOf(2));
Whichever you use is your choice. StringBuilder is faster, but the speed difference is marginal. I prefer to use the +
operator (which does a StringBuilder.append(String.valueOf(X)))
and find it easier to read.
无论您使用哪种,都是您的选择。StringBuilder 更快,但速度差异很小。我更喜欢使用+
运算符(它执行 aStringBuilder.append(String.valueOf(X)))
并发现它更易于阅读。
回答by Ved Prakash
public class StringFormat {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("================================");
for(int i=0;i<3;i++){
String s1=sc.next();
int x=sc.nextInt();
System.out.println(String.format("%-15s%03d",s1,x));
}
System.out.println("================================");
}
}
outpot "================================"
ved15space123 ved15space123 ved15space123 "================================
输出点“================================”
ved15space123 ved15space123 ved15space123 “============ ======================
Java solution
Java解决方案
The "-" is used to left indent
The "15" makes the String's minimum length it takes up be 15
- The "s" (which is a few characters after %) will be substituted by our String
- The 0 pads our integer with 0s on the left
- The 3 makes our integer be a minimum length of 3
“-”用于左缩进
“15”使字符串的最小长度为 15
- “s”(% 后的几个字符)将被我们的字符串替换
- 0 在左边用 0 填充我们的整数
- 3 使我们的整数最小长度为 3
回答by Tomasz Modelski
I've wrote my simple method for it :
我已经为它写了我的简单方法:
public class SomeCommons {
/** Message Format like 'Some String {0} / {1}' with arguments */
public static String msgFormat(String s, Object... args) {
return new MessageFormat(s).format(args);
}
}
so you can use it as:
所以你可以将它用作:
SomeCommons.msfgFormat("Step {1} of {2}", 1 , "two");
回答by Felipe Bejarano
This solution worked for me. I needed to create urls for a REST client dynamically so I created this method, so you just have to pass the restURL like this
这个解决方案对我有用。我需要为 REST 客户端动态创建 url,所以我创建了这个方法,所以你只需要像这样传递 restURL
/customer/{0}/user/{1}/order
and add as many params as you need:
并根据需要添加尽可能多的参数:
public String createURL (String restURL, Object ... params) {
return new MessageFormat(restURL).format(params);
}
You just have to call this method like this:
你只需要像这样调用这个方法:
createURL("/customer/{0}/user/{1}/order", 123, 321);
The output
输出
"/customer/123/user/321/order"
“/customer/123/user/321/order”
回答by DefconT34
I wrote this function it does just the right thing. Interpolate a word starting with $
with the value of the variable of the same name.
我写了这个函数,它做了正确的事情。插入一个$
以同名变量的值开头的单词。
private static String interpol1(String x){
Field[] ffield = Main.class.getDeclaredFields();
String[] test = x.split(" ") ;
for (String v : test ) {
for ( Field n: ffield ) {
if(v.startsWith("$") && ( n.getName().equals(v.substring(1)) )){
try {
x = x.replace("$" + v.substring(1), String.valueOf( n.get(null)));
}catch (Exception e){
System.out.println("");
}
}
}
}
return x;
}