问题描述
我正在练习 ArrayList
.我正在尝试使每次 is
都在ArrayList中,然后紧跟着 not
.例如, [是天空,是,这是蓝色,是,是,不是]
,通过该方法运行后会显示为 [不是天空,是,不是,这不是蓝色,是不是不是,不是不是]
.但是,现在我的代码不会改变.我是Java的新手,所以我非常感谢任何指针!
I'm practicing ArrayList
's. I'm trying to make it so that every time is
is in the ArrayList, it is then followed with not
. For instance [is sky, is, this is blue, is is, is not]
after running through the method comes out as [is not sky, is not, this is not blue, is not is not, is not not]
. However, with my code right now it does not change. I am new to Java, so I would really appreciate any pointers!
class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("is sky");
list.add("is");
list.add("this is blue");
list.add("is is");
list.add("is not");
System.out.println(replace(list));
}
public static ArrayList<String> replace(ArrayList<String> list) {
for (int i = 0; i < list.size(); i++) {
if (list.subList(i, i + 1).equals("is")) {
list.add(i + 1, " not");
}
}
return list;
}
}
推荐答案
首先解决最简单的情况.暂时忘记列表,仅用一个 String
替换即可.
First solve the simplest case. Forget the list for a moment and do the substitution with just one String
.
String replaceOne(String original) {
return original.replace("is", "is not");
}
测试此方法.
String replaced = replaceOne("sky is");
如果此替换的
变量等于 sky不
,则测试通过.
The test passes if this replaced
variable is equal to sky is not
.
一旦您保证了这一点,请继续阅读带有列表的一般情况.
Once you've guaranteed that, move on to the general case, with a list.
void replaceMany(ArrayList<String> original) {
for (int i = 0; i < original.size(); i++) {
original.set(i, replaceOne(original.get(i)));
}
}
请注意,如果您是在静态方法中运行此方法,则上述方法必须是静态的(即 static void
, static String
).
Note that if you're running this inside a static method, the above methods need to be static (i.e. static void
, static String
).
使用Java 8,您还可以以不同的方式解决此问题.除了使用数组列表上的 set
方法,您还可以使用lambda和一个收集器来获取修改后的列表(保留原始列表并使用修改后的字符串获取另一个列表).像这样:
With Java 8 you could also solve this problem differently. Instead of using the set
method on the array list, you could use lambdas and a collector to get a modified list (preserve the original and get another list with the modified strings). Something like:
List<String> replaced = original.stream()
.map(s -> replaceOne(s))
.collect(Collectors.toList());
这篇关于如何在Java的arraylist中的单词中间添加字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!