因为字符而从数组中删除项



假设你有一个这样的数组: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
    }
  }
}

我不确定我的逻辑是否有效,甚至不确定我是否在正确的轨道上。任何回复都会很有帮助。多谢。

筛选数组的一种简单方法是在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);

您可以直接使用String类的contains()方法来检查字符串中是否存在"e"。这将节省额外的for循环

如果你使用数组列表,这将是简单的。导入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
            }
    }

问题是,您需要在知道其中有多少元素之前声明和实例化String数组(因为在循环之前您不知道有多少字符串不包含'e')。相反,如果使用ArrayList,则不需要事先知道所需的大小。这是我的代码从开始到结束。

String[]事件={"你好"、"再见"、"明天"};

    //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));

最新更新