【发布时间】:2020-03-24 11:04:22
【问题描述】:
我正在尝试用 Java 编写一个 madlibs 程序。有一个方法接受模板字符串、该字符串中所有占位符的 ArrayList 以及将替换这些模板的所有用户输入的 ArrayList 作为参数。
方法如下:
private String replacePlaceHolder(String template, ArrayList<String> placeholders, ArrayList<String> replacements){
for (int i = 0; i < placeholders.size(); i++){
template = template.replace(placeholders.get(i), replacements.get(i));
}
return template;
}
问题是,该方法是用替换替换所有出现的给定模板,例如“[形容词]”,而不仅仅是第一个。我尝试改用template = template.replaceFirst(placeholders.get(i), replacements.get(i)),但它用所有用户输入替换了第一个占位符,并忽略了其余部分。
这是我使用的模板:
Computer programming, also known as [-ing Verb], is a
process that leads from a [Adjective] problem
to an executable [Noun].
Programming often involves [-ing Verb],
[-ing Verb], and [-ing Verb], and can be learned
by anyone!
Source code is written in a programming language,
such as [Animal]code, or Java.
The first ever programmer was [Name of Celebrity],
who invented [Plural Noun] in the year [Year].
Since then, programming has become a
[Adjective] practice all across the world.
我知道占位符的 ArrayList 与模板中的占位符匹配,并且该 ArrayList 与用户输入的 ArrayList 长度相同。
我应该做些什么不同的事情?
【问题讨论】:
-
@kaya3 我试过
replaceFirst()没用,所以我不相信这个问题是重复的。 -
好吧,你的问题是如何替换第一次出现而不是每次出现,所以它是重复的。如果这不起作用,那么您可能想做其他事情,与您在问题中要求的不同。
标签: java arraylist string-algorithm