Search code examples
javastringindexofdigits

Java - How to search a string for 6 random numbers


I have a (large) string file in my application which contains a series of random character [a-Z] and [0-9] but also ";","/", "?", ":" and "@". I would like my application to tell me the nearest position where 6 digits are displayed consecutively ( like "105487" or "558463").

What would be the best way to achieve this? Thank you for looking into this.


Solution

  • An effective approach would be to iterate the characters of the string and test if each is a digit. Upon finding a match continue to look for the rest of the sequence. Something like

    int nDigits=0, i = 0;
    CharacterIterator it = new StringCharacterIterator("very long string123456");
    for (char ch=it.first(); ch != CharacterIterator.DONE; ch=it.next()) {
      i++;
      nDigits = (ch.isDigit() ? nDigits++ : 0);
      if (nDigits == 5) {
          // DONE. Position is "i"
      }
    }