简体   繁体   中英

Search and replace in Array using index of another 2D array

I need to search and replace through an array of strings using search and replace matches listed in a separate 2D array .

--------Edit--------

Final Code:

    String[][] searchLibrary;    // calls the replaces array from the LibToArray method
    searchLibrary= LibToArray();

    for(int i = 0; i <searchLibrary.length; i++){
        {
        fileContents.set(i, fileContents.get(i).replace(searchLibrary[i][0], searchLibrary[i][1]));
        }       
        }
    for (String row : fileContents) {
        System.out.println(row);        // print array to cmd
        }

OK, first: You can define your replace the way you did (but change the names back to oldstr and newStr--or better, oldStr for consistency, with an upper-case S. You can't start an identifier with a digit 2.) Then outside, go through your 2D array like this:

String[][] twoDimArray;
// something that sets up twoDimArray

for (String[] row : twoDimArray)
     replace (toSearchIn, row[0], row[1]);

// or, using an index:

for (int i = 0; i < twoDimArray.length; i++)
     replace (toSearchIn, twoDimArray[i][0], twoDimArray[i][1]);

I'm not sure if that's what you want since I'm not clear from the description. If I'm close, twoDimArray is an array of arrays (Java doesn't have "pure" two-dimensional arrays); specifically, it's an array of unknown length, where each element of the array is an array of length 2. So twoDimArray[i] is one element of the array, and the element is an array of length two, and you can use 0 or 1 to index it.

Second: You may be using the wrong contains(). There's a contains() defined both for ArrayList and String. Your code uses the ArrayList version. For ArrayList, it will return true if any element of the array matches its argument. That doesn't look right. If you're stepping through the whole array, you don't want to search the entire array on every step. For String, it returns true if the string contains the argument as a substring. You'd have to write it like this:

if (toSearchIn.get(i).contains(oldstr))

since toSearchIn.get(i) is a string. But I'd just leave it out, because if contains() returns false , replace() will just leave the string alone anyway, which is what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM