简体   繁体   English

Java - 带连字符的String.format

[英]Java - String.format with hyphen

Writing my first real bit of Java code and I'm struggling to figure out this one out. 编写我的第一个真正的Java代码,我正在努力弄清楚这个。

I need to generate a string in set format: 我需要以set格式生成一个字符串:

code:100-100-100

I'm using String.format to try and generate it: 我正在使用String.format来尝试生成它:

String templateFormat = "code:%1$-%2$s-100";
String code = String.format(templateFormat, "100", "100", "100");

But the hyphen has special meaning to the formatter, how can I escape it? 但连字符对格式化程序有特殊意义,我怎么能逃脱呢?

Tried to escape the hyphen with a "\\" but Eclipse rightly informed me: 试图用“\\”来逃避连字符,但Eclipse正确告诉我:

Invalid escape sequence (valid ones are \\b \\t \\n \\f \\r \\" \\' \\ ) 无效的转义序列(有效转义序列为\\ b \\ t \\ n \\ f \\ r \\“\\ \\ \\ \\)

Cheers 干杯

The problem isn't with your hyphen so much as with your templateFormat: 问题不在于你的连字符,而在于你的templateFormat:

You have... String templateFormat = "code:%1$-%2$s-100"; 你有...... String templateFormat = "code:%1$-%2$s-100";

Where you need... String templateFormat = "code:%1$s-%2$s-100"; 你需要的地方...... String templateFormat = "code:%1$s-%2$s-100";

Notice the missing s in the %1$ part 注意%1$部分中缺少的s

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM