字符串替换问题
我拥有的:
我有一个文本“嗨{0},我的名字是{1}。”
我有一个List
我正在尝试将 Peter 放在有 {0} 的地方,将 Josh 放在有 {1} 的地方。
我想要什么:
Hi Peter, my name is Josh.
我有什么想法可以做到吗?
What I have:
I've got a text "Hi {0}, my name is {1}."
I've got a List<String> names = Arrays.asList("Peter", "Josh");
I'm trying to fit Peter where there's a {0} and Josh where there's a {1}.
What I want:
Hi Peter, my name is Josh.
Any ideas of how could I do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
MessageFormat 类是你的朋友。 http://download.oracle.com/javase /1.5.0/docs/api/java/text/MessageFormat.html
MessageFormat class is your friend. http://download.oracle.com/javase/1.5.0/docs/api/java/text/MessageFormat.html
最简单的可能是在循环中使用 String.replaceXX 操作之一。例如,
这有点低效,因为与使用 StringBuffer 或类似的东西相比,重复创建新字符串是一种不好的形式,但通常这种形式的文本替换是低频操作,因此简单性胜过效率。
Probably simplest would be to use one of the String.replaceXX ops in a loop. Eg,
This is a bit inefficient, since it's bad form to repeatedly create new Strings vs using a StringBuffer or some such, but generally text replacement of this form would be a low-frequency operation, so simplicity trumps efficiency.
你会做这样的事情。
只需 2 行代码即可完成。
You would do something like this.
and that would be it in just 2 lines of code.
如果我太从字面上理解你并且你想要一些更通用的东西,我很抱歉,但这将完全按照你的要求进行。
My apologies if I'm taking you too literally and you wanat something more generic but this will do exactly as you asked.
我假设您的列表将具有正确数量的元素。
I'm assuming that your list will have the correct number of elements.