问题描述
我正在练习 ArrayList
的.我试图做到这样,每次 is
在 ArrayList 中时,后面跟着 not
.例如[is sky, is, this is blue, is, is not]
运行该方法后,结果为[is not sky, is not, this is not blue, is不是不是,不是不是]
.但是,现在我的代码不会改变.我是 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");
如果这个replaced
变量等于sky is not
,则测试通过.
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
方法之外,您还可以使用 lambdas 和收集器来获取修改后的列表(保留原始列表并使用修改后的字符串获取另一个列表).类似的东西:
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中的单词中间添加字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!