简体   繁体   中英

Convert a string to int in Java without allocating a String

I have thousands of lines of text file, similar to this:

0000:0010:1111:3000
0003:0010:1113:3000
0004:0010:1188:3009

and so on, where the data is to be parsed as ints.

The most obvious way to do it is by using Integer.parseInt(String) . However, it needs a String , and since String s are immutable, we have to allocate again and again String s just to convert them to ints.

It is to be run in a mobile device where allocating a String and letting the GC run takes a considerable effort.

I am hoping to be able to have a method like parseInt(char[] chars, int offset, int length) so that we don't need to do allocations. Is that possible? Is there any implementation in standard Java/JDK/Android library that can already do that?

You could use a Scanner and call useDelimiter(String) to set your separator(s). Something like,

String str = "0000:0010:1111:3000\n" + "0003:0010:1113:3000\n"
        + "0004:0010:1188:3009";
Scanner sc = new Scanner(str);
sc.useDelimiter("[:|\\s]+"); // <-- one or more colon or whitespace
while (sc.hasNextInt()) {
    System.out.printf("%04d%n", sc.nextInt()); // <-- format to 4 digits with
                                               //     leading zeros.
}

It's quite simple to parse int from char array, this is demo code:

public static int parseInt(char[] chars, int offset, int length) {
    int r = 0;
    for (int i = offset; i < offset + length; ++i) {
        r *= 10;
        r += chars[i] - '0';
    }

    return r;
}

You can add some security check for array length and make sure the char is really digits if you like.

If you really care that much about performance, you'll have to write your own code to parse the ints. eg

public static int parseInt(String s, int startPos, int len) {
  // code omitted, it would be simple
}

Where the String s is your entire file (or perhaps one line thereof). Search for end of lines and colons and get your numbers. Or use a char[] as in your idea. I don't know of a built in Java class to do this but the code is simple enough - something you learn in Java 1 at school.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM