AFAIK there is no efficient way in standard Java libraries for parsing an integer from a substring without actually creating a new string containing the substring.
I am in a situation where I process millions of integers from strings, and I don’t really want to create new strings for each substring. Copy overhead I do not need.
Given the string s, I need a method like:
parseInteger(s, startOffset, endOffset)
with semantics like:
Integer.parseInt(s.substring(startOffset, endOffset))
Now I know that I can do this quite trivially:
public static int parse(String s, int start, int end) { long result = 0; boolean foundMinus = false; while (start < end) { char ch = s.charAt(start); if (ch == ' ') ; else if (ch == '-') { if (foundMinus) throw new NumberFormatException(); foundMinus = true; } else if (ch < '0' || ch > '9') throw new NumberFormatException(); else break; ++start; } if (start == end) throw new NumberFormatException(); while (start < end) { char ch = s.charAt(start); if (ch < '0' || ch > '9') break; result = result * 10 + (int) ch - (int) '0'; ++start; } while (start < end) { char ch = s.charAt(start); if (ch != ' ') throw new NumberFormatException(); ++start; } if (foundMinus) result *= -1; if (result < Integer.MIN_VALUE || result > Integer.MAX_VALUE) throw new NumberFormatException(); return (int) result; }
But this is not so. I would rather get this from a trusted, supported third-party library. For example, parsing lengths and correctly processing Long.MIN_VALUE is a bit subtle, and I cheat on above by parsing ints in longs. And above there is still an overflow problem if the integer integer is greater than Long.MAX_VALUE.
Is there such a library?
My search has changed a bit.
java string int parsing
Barry kelly
source share