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.
You could use regex.
String regex = "(\\d{6})";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(YOU STRING HERE);
// Check all occurrences
while (matcher.find()) {
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end());
System.out.println(" Found: " + matcher.group());
}
This would do the job.
(Code sample from here)
Use Character.isDigit while iterating the string's characters and then count a number up until you have found 6 consecutive numbers or reset it if the sequence breaks. Keep track of the index and you can simply calculate the nearest position by subtraction.
This is not very efficient, but I think O(n) is sufficient if the strings are not too large. For optimization take a look on what Luiggi Mendoza has suggested in the comments.
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"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With