Auceris
Auceris

Reputation: 5

Only Collects First Index

So I'm supposed to make a list that contains the character that follows each non-tail occurrence of a pattern in a text. The character stored at index n of the list must be the character that followed the nth non-tail occurrence of the pattern.

Ex: The test case getCharsThatFollowPattern("abcabdabcab", "ab") should return the ArrayList ['c', 'd', 'c'].

I'm having problems trying to get the list to iterate through the pattern text. I get ['a', 'a', 'a'] in my test case instead of ['c', 'd', 'c'].

public static ArrayList<Character> getCharsThatFollowPattern (String text, String pattern) { 

  ArrayList<Character> character = new ArrayList<Character>(); 
  int i = 0; 

  while (i < text.length()) 
  { 
    if (i < text.length()) 
    { 
      character.add(text.charAt(text.indexOf(pattern, i))); 
      i = i + text.indexOf(pattern, i) + pattern.length(); 
    } 
  } 

  return character;
}

Why wont it iterate through? :(

Upvotes: 0

Views: 57

Answers (1)

Kaan
Kaan

Reputation: 5784

Your intent is to find a substring pattern inside the larger text value, and then add each of those characters to an array. There are a few things going on in your code, so I tried to create the simplest example that shows how to get it to work, but exclude things that you were already fine with (like creating an array and populating values).

The code below finds where the next pattern starts – indexOfNextPatternStart – that would be where ever "ab" occurs next. Then it adds the length of "ab" itself to get whatever index is after that. So in your text example, it starts with "abc" – "ab" is clearly at the front, but you want the index of "c". That's what indexOfCharAfterPattern contains. At that point, you've got the character isolated. In my example, I'm storing that temporarily as charAfterPattern and printing it out.

I added the if (indexOfCharAfterPattern < text.length()) check to protect against the last "ab" in text. There's nothing after that last "ab", so trying to look ahead for the next character won't work.

public static void printThatFollowPattern(String text, String pattern) {
    int i = 0;
    while (i < text.length()) {
        int indexOfNextPatternStart = text.indexOf(pattern, i);
        int indexOfCharAfterPattern = indexOfNextPatternStart + pattern.length();

        if (indexOfCharAfterPattern < text.length()) {
            char charAfterPattern = text.charAt(indexOfCharAfterPattern);
            System.out.println("charAfterPattern: " + charAfterPattern);
        } else {
            break;
        }

        i = indexOfCharAfterPattern + 1;
    }
}

Upvotes: 1

Related Questions