简体   繁体   中英

Using traditional for loop to remove certain elements within a string array

Assignment description: Write a traditional for loop that checks each element for the String “Meg”, if found in the array, remove it, shift the remaining elements, and display the array of names.

Cannot wrap my head around this concept. I understand how to initialize an array and reassign elements outside of a loop, but cannot figure out how to replace them within a for loop. This is what I have. This is my first programming class and I am struggling pretty bad. If someone with more experience could thoroughly explain the process of removing "Meg" I would appreciate it more than you know.

Program:

public class CustomerListerArray{

  public static void main(String[] args){

    String[] customerNames = new String[7];

    customerNames[0] = "Chris";
    customerNames[1] = "Lois";
    customerNames[2] = "Meg";
    customerNames[3] = "Peter";
    customerNames[4] = "Stewie";

    for(String element : customerNames){
      System.out.println(element);
    }
    System.out.println();

    customerNames[6] = customerNames[4];
    customerNames[5] = customerNames[3];
    customerNames[4] = "Brian";
    customerNames[3] = "Meg";

    for(String element : customerNames){
      System.out.println(element);
    }

    System.out.println();
    //******************************************************************
    for(int i = 0; i < customerNames.length; i++) {

      if(customerNames.equals("Meg")){
        customerNames[i] = null;

        for(int j = i; customerNames.equals(null); j++){
          customerNames[i] = customerNames[j + 1] ;
          System.out.println(customerNames[i]);
        }
      }
    }//******************************************************************
  }
}

The easiest way to do this problem is declare another array, of size customerNames , iterate through customerNames , if customerName is "Meg", then do nothing, otherwise add it to the new array. At the end you will have an array with all names except "meg". Within this one for loop you can count the non-"meg" names.

Another inefficient ways to do this would be every time you find "meg", you shift all elements after up one. So if you find "meg" at i=2 you iterate through the array starting at 2, customerNames[i]=customerNames[i+1] this will shift all the elements one by one. This method will work because you are replacing the index at which "meg" is stored at with the element right after.

Think of it like a sequence of boxes, when you take a box out in between, you want to move all of the other boxes up to get rid of the empty space. Or even better take a column in excel numbers 1-10, if you empty a random cell, you would have to move each one up one by one to fill the gap. (Obviously there is a work around in excel, just an example)

I would give you the solutions to it, but as a beginner going through this pain and figuring it out yourself is ESSENTIAL in my eyes.

There are a few different things to understand in order to solve this problem.

  1. Finding a value within the array
  2. Removing the value from the array
  3. Shifting the values beyond that point to fill the gap

Finding a Value

You've already figured out how to iterate over the array. That's the hardest part of this problem. You get step 1 almost for free after that.

for (int i = 0; i < array.length; i++) {
    String currentString = array[i];
}

When you're iterating, or traversing the array, you have access to the string at each position by using your for loop's index variable ( i in my example above). The string at position i is array[i] .

If you're searching for a particular string, just compare each string along the way to your search value. To compare strings, check string1.equals(string2) .

So what we have so far is:

String searchStr = "FindMe";
for (int i = 0; i < array.length; i++) {
    if (searchStr.equals(array[i])) {
        System.out.println("Found!");
    }
}

Pretty easy. We traversed the array, found the value that we wanted, and printed a little message to the console when we found what we were looking for. So we're halfway there.

Removing a Value

So we identified two more steps that we'd need to do to solve this problem. But it turns out that we can do both steps 2 and 3 at the same time! Let's think about why that's possible. Step 2 is asking us to remove a value. In Java arrays, we remove values by overwriting them with something else. Since step 3 is telling us to shift our values left, we actually end up overwriting the value from Step 2 anyway!

Consider this array, if we want to remove Y :

|X|Y|Z|

We could first 'remove' Y :

|X|_|Z|

And then shift Z left:

|X|Z|_|

Or we could shift Z to the left in a single step:

|X|Y|Z| => |X|Z|_|

We'll try the second approach, since it seems simpler. So let's find the string that we're looking for and then, for every element to it's right, start shifting element to the left by one position.

int index = 0;
String searchStr = "FindMe";

for (int i = 0; i < array.length; i++) {
    if (searchStr.equals(array[i])) {
        // Make a note of where we found it, then stop searching
        index = i;
        break;
    }
}

for (int i = index; i < array.length - 1; i++) {
    // Replace each value with the next value
    array[i] = array[i+1];
}

Now we have effectively shifted the values left by removing each value starting at our search string, and replacing it with the value to its right.

We still have one problem though. You'll notice the second for loop ends at array.length - 1 . We replaced each value with the one to its right...but the last element had nothing to its right. If try to replace it with the value at array[i+1] , we would get an ArrayIndexOutOfBoundsException . You can't look at a value beyond the edge of your array. So what do we do in that situation? It's pretty simple actually:

array[array.length - 1] = null;

Simply overwrite the last value with null , which is how we represent the concept of 'nothing' in Java. We've already shifted that last value to the left, so we just need to replace it with null to complete the removal process.

And we now have an array that no longer contains our search string!


PS What if you don't find the string in the array?!

Of course, as we deal with increasingly complicated problems, we have to account for invalid input data. What happens if I make it to the end of the array and never find my string? Simple: there's nothing to remove, so our work is done! We just tweak our code so there's an if statement around our second for loop:

int index = -1;
String searchStr = "FindMe";

for (int i = 0; i < array.length; i++) {
    if (searchStr.equals(array[i])) {
        index = i;
        break;
    }
}

if (index > -1) {
    for (int i = index; i < array.length - 1; i++) {
        array[i] = array[i+1];
    }
}

array[array.length - 1] = null;

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