简体   繁体   中英

How would I create an iterator that reverses the given string?

I'm trying to create a "Reverse Iterator" in Java, which takes a string and outputs each string in reverse order. This is my code now:

//a b c d -> d c b a
class ReverseIterator implements Iterator<String> {
  String given;
  int index;
  ReverseIterator(String given) {
    this.given = given;
    this.index = 0;
  }

  // is there a next?
  public boolean hasNext() {
    return this.index <= this.given.length();
  }

  // gets the next item
  // effect: advances the index by one
  public String next() {
    String answer = this.given.substring(given.length() - this.index, given.length() - this.index - 1);
    this.index = index + 1;
    return answer;
  }
}

I'm getting a String index out of range: -1 , but I'm not sure how to fix my algorithm so it works.

So two things are wrong.

First return this.index <= this.given.length(); is going to produce an error when you reach the last character, as String is zero indexed, ie 0 to length - 1

Second

this.given.substring(given.length() - this.index, given.length() - this.index - 1);

Produces an index range where the endIndex is less then the beginIndex (hence the error String index out of range: -1 )

So, if index is 5, you're trying to get the substring starting at 5 and end at 4 , which is invalid. You want switch those around, something more like...

public String next() {
    int from = given.length() - this.index - 1;
    int to = given.length() - this.index;
    String answer = this.given.substring(from, to);
    this.index = index + 1;
    return answer;
}

Most of this was debugged with a series of System.out.println statements, it's really important that when you start hitting issues like this, that you take the time to break you variables out (like I did above) and inspect there actual values, it's really helpful for highlighting the silly mistakes we all make

Oh, also, I agree String#charAt would seem to make more sense

Your arguments in the substring method are mixed up which is causing the exception:

For a given string of length 5, you want to access the substring from index 5 to 4 which is not possible.

If you change the arguments your next() method will return the last char as a string.

now you have to add the hasNext() method and a loop to your code and you should be good to go.

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