EDIT: for the sake of knowledge, I ran different solutions on the same (old) machine, with 5,000,000 iterations (one zero removed from the OP question), here are the results:
Total execution time (ms) via the Martijn Courteaux algorithm: 2562
Total execution time (ms) via Char comparison: 6891
Total lead time (ms) Regular expression (with parenthesis): 12937
Total lead time (ms) Regular expression (without brackets): 12297
This is about twice as fast as the regular expression:
startTime = System.currentTimeMillis(); for (int i = 0; i < COUNT; i++) { // Output is list of 1, 9, 1 Demo.extractNumbersViaCharComparison(INPUT); } System.out.println("Total execution time (ms) via Char comparison: " + (System.currentTimeMillis() - startTime));
[...]
static List<Integer> extractNumbersViaCharComparison(final String text) { final List<Integer> result = new ArrayList<Integer>(); char[] chars = text.toCharArray(); StringBuilder sB = new StringBuilder(); boolean previousWasDigit = false; for (int i = 0; i < chars.length; i++) { if (Character.isDigit(chars[i])){ previousWasDigit = true; sB.append(chars[i]); } else { if (previousWasDigit){ result.add(Integer.valueOf(sB.toString())); previousWasDigit = false; sB = new StringBuilder(); } } } if (previousWasDigit) result.add(Integer.valueOf(sB.toString())); return result; }
By the way, another solution is much more elegant +1
source share