假设你有一个这样的数组:String[] theWords = {"hello", "good bye", "tomorrow"}
。我想删除/忽略数组中包含字母'e'的所有字符串。我该怎么做呢?我的想法是:
for (int arrPos = 0; arrPos < theWords.length; arrPos++) { //Go through the array
for (int charPos = 0; charPos < theWords[arrPos].length(); charPos++) { //Go through the strings in the array
if (!((theWords[arrPos].charAt(charPos) == 'e')) { //Finds 'e' in the strings
//Put the words that don't have any 'e' into a new array;
//This is where I'm stuck
}
}
}
我不确定我的逻辑是否有效以及我是否在正确的轨道上。任何回复都会有所帮助。非常感谢。
答案 0 :(得分:1)
过滤数组的一种简单方法是在for-each循环中使用if
填充ArrayList
:
List<String> noEs = new ArrayList<>();
for (String word : theWords) {
if (!word.contains("e")) {
noEs.add(word);
}
}
Java 8中的另一种方法是使用Collection#removeIf
:
List<String> noEs = new ArrayList<>(Arrays.asList(theWords));
noEs.removeIf(word -> word.contains("e"));
或使用Stream#filter
:
String[] noEs = Arrays.stream(theWords)
.filter(word -> !word.contains("e"))
.toArray(String[]::new);
答案 1 :(得分:0)
您可以直接使用String类的contains()
方法来检查字符串中是否存在“e”。这样可以节省额外的循环次数。
答案 2 :(得分:0)
如果使用ArrayList,那将很简单。
导入import java.util.ArrayList;
ArrayList<String> theWords = new ArrayList<String>();
ArrayList<String> yourNewArray = new ArrayList<String>;//Initializing you new array
theWords.add("hello");
theWords.add("good bye");
theWords.add("tommorow");
for (int arrPos = 0; arrPos < theWords.size(); arrPos++) { //Go through the array
if(!theWords.get(arrPos).contains("e")){
yourNewArray.add(theWords.get(arrPos));// Adding non-e containing string into your new array
}
}
答案 3 :(得分:0)
你遇到的问题是你需要先声明并实例化String数组,然后才能知道它中有多少个元素(因为你不知道有多少个字符串不包含&#39; e&#39;在完成循环之前)。 相反,如果使用ArrayList,则不需要事先知道所需的大小。这是我的代码从头到尾。
String [] theWords = {&#34; hello&#34;,&#34;再见&#34;,&#34;明天&#34; };
//creating a new ArrayList object
ArrayList<String> myList = new ArrayList<String>();
//adding the corresponding array contents to the list.
//myList and theWords point to different locations in the memory.
for(String str : theWords) {
myList.add(str);
}
//create a new list containing the items you want to remove
ArrayList<String> removeFromList = new ArrayList<>();
for(String str : myList) {
if(str.contains("e")) {
removeFromList.add(str);
}
}
//now remove those items from the list
myList.removeAll(removeFromList);
//create a new Array based on the size of the list when the strings containing e is removed
//theWords now refers to this new Array.
theWords = new String[myList.size()];
//convert the list to the array
myList.toArray(theWords);
//now theWords array contains only the string(s) not containing 'e'
System.out.println(Arrays.toString(theWords));