使用“?”格式化字符串的方法java中完整字符串的参数?
例如,我想用方法实现类
public class Logger {
public void info(String message, String[] params) {
}
}
如果输入是
new Logger().info("Info: param1 is ? , param2 is ?", new String[] {"a", "b"});
输出必须是
Info: param1 is a , param2 is b
什么是最简单的实现方法?
For example I want to implement class with method
public class Logger {
public void info(String message, String[] params) {
}
}
If input is
new Logger().info("Info: param1 is ? , param2 is ?", new String[] {"a", "b"});
Output must be
Info: param1 is a , param2 is b
What is the easiest way to implement it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
以下代码将按照您的要求进行操作。
但是,您应该考虑使用正确的格式占位符而不是“?”。例如:
两个版本都会打印:
The following code does as you require.
However, you should consider using correct formatting place-holders instead of '?'. For instance:
Both versions will print:
如果您不必担心转义
'?'
,并且无法使用 printf() 样式格式字符串,则可以使用:像这样:
Which prints:
苹果之于香蕉就像夏娃之于中午
如果您需要更复杂的逻辑(例如转义),那么您可能需要基于正则表达式
模式
的成熟搜索和替换。If you don't have to worry about escaping the
'?'
, and you can't use printf() style format strings, you could get away with:Like so:
Which prints:
apple is to banana as eve is to noon
If you need more sophisticated logic, such as escaping, then you'll probably want a full-blown regexp
Pattern
-based search and replace.在 params[] 的循环中使用正则表达式查找每个“?”在您的字符串中并将其替换为当前参数。谨防空值并找到合适的逃生方法? (猜猜\?会带来一些麻烦,更好吗??)
in a loop on params[] use regexp to find every '?' in your string and substitute it with the current param. Beware of nulls and find a proper way to escape ? (guess \? will give some trouble, better ??)
您可以使用
String.format(String format, Object ... args)
方法。您可以使用 C 风格的%x
格式来代替使用?
,其中x
可以是d
(例如int)、s
(字符串)等示例< /a>.
另外,您还可以查看
Formatter.format
类方法。它显示了所有可接受的格式化标志(String.format()
方法使用Formatter
进行格式化)。You can use the
String.format(String format, Object ... args)
method for this. Instead of using a?
, you can do C style%x
format, wherex
can bed
(for int),s
(for string), etc.Example.
Also, you can view the
Formatter.format
class method. It shows you all formatting flags acceptale for formatting (String.format()
method usesFormatter
to do the formatting).