Skip to content

Remove a specific row from a 2D Array

Given a 2D array and a string, how can I remove a row which does not contain a specific string? So far, I created a nested for loop which iterates through the array, adding all adjacent elements(except the string itself) to an ArrayList. However, I do not want to include elements from rows that exclude the specified string.

String letters[][] = 
        {"a", "b"}, 

If the string is “a”, the list should include “b”. However, my list also includes “s” because it is not equal to the string. How can I write my code so that only elements that share the same row as the specified string are added to the list?



Based on your approach, the simple answer is to go through each row potentially twice if it should be added, with the first iteration you want to determine if the row should be added. With the second, you add all of the elements in the row

String[][] letters = ...;
for (int i = 0; i < letters.length; i++) {
    boolean addRow = false;
    for (int j = 0; j < letters[i].length; j++) {
        //if you find the string, set addRow to true;
    if (addRow) {
        //add all elements in the row