gpt4 book ai didi

java : remove words from ArrayList

转载 作者:行者123 更新时间:2023-12-02 03:04:37 25 4
gpt4 key购买 nike

假设我的单词数组是words={"a","the","in","if","are","it","is"},我的ArrayList包含这样的字符串{"a"表格在这里”,“书已售出”,“如果可读”}。我想从 arrayList 中删除 array 的所有单词。预期输出将是 ArrayList,如 {"table here","books sell","re​​aded"}。

到目前为止我已经尝试过:

public static void main(String[] args) {
String[] words = {"a","the","in","if","are","it","is"};
List<String> wordList = new ArrayList<String>(Arrays.asList(words));
String[] tArray = {"a table is here", "books are sold","if it is readable"};
List<String> list = new ArrayList<String>(Arrays.asList(tArray));

for (int i = 0; i < list.size(); i++) {
String[] tArrays = list.get(i).split(" ");
List<String> line = new ArrayList<String>(Arrays.asList(tArrays));
for (int c = 0; c < wordList.size(); c++) {
if (wordList.get(c).equals(line.get(i))) {
line.remove(i);
i--;
break;
}
}//end for
list.set(i, String.join(" ", line));
}//end for
for(String string : list)
{
System.out.println(string);
}
}

但没有给出预期的输出。相反,给出错误“java.lang.ArrayIndexOutOfBoundsException:-1”

最佳答案

您应该使用 line.size() 迭代基于“”拆分后的所有单词。

for (int i = 0; i < list.size(); i++) {
String[] tArrays = list.get(i).split(" ");
List<String> line = new ArrayList<>(Arrays.asList(tArrays));
for (int c = 0; c < wordList.size(); c++) {
if (wordList.get(c).equals(line.get(i))) { // you get i for indexes corresponding to the sentence element and not `line` elements as created above
line.remove(i); // i is iterated over the list of sentences in your case 3, would start from i=0
i--; // you change it to '-1' and get IndexOutOfBounds
break;
}
}//end for
list.set(i, String.join(" ", line));
}//end for
<小时/>

虽然没有经过测试,但你可以做类似的事情 -

public static void main(String[] args) {
String[] words = {"a", "the", "in", "if", "are", "it", "is"};
List<String> wordList = new ArrayList<>(Arrays.asList(words));
String[] tArray = {"a table is here", "books are sold", "if it is readable"};
List<String> list = new ArrayList<>(Arrays.asList(tArray));

for (int i = 0; i < list.size(); i++) {
String[] tArrays = list.get(i).split(" ");
List<String> line = new ArrayList<>(Arrays.asList(tArrays));
for (String lineElement : line) {
if (wordList.contains(lineElement)) {
line.remove(lineElement);
}
}

list.set(i, String.join(" ", line));
}

for (String string : list) {
System.out.println(string);
}
}

关于java : remove words from ArrayList<String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41907518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com