2

Is it possible in Java to efficiently read an integer from random position of the string? For instance, I have a

String s = "(34";
if (s.charAt(0) == '(')
{
    // How to read a number from position = 1 to the end of the string?
    // Of course, I can do something like
    String s1 = s.substring(1);
    int val = Integer.parseInt(s1);
}

but it dynamically creates a new instance of string and seems to be too slow and performance hitting.

UPDATE

Well, to be precise: I have an array of strings in form "(ddd" where d is a digit. So I do know that a number starts always from pos = 1. How do I efficently read these numbers?

3
  • @Nick Please apply more examples of source data and results you want to get Commented May 2, 2013 at 7:41
  • Read into a StringBuilder object in the first place, atleast that'll save you the overheads of creating a new string object everytime. Commented May 2, 2013 at 7:57
  • First, thank you all. I have updated my question to be clear. Commented May 2, 2013 at 8:03

4 Answers 4

1
Integer.parseInt(s1.replaceAll("[\\D]", ""))
Sign up to request clarification or add additional context in comments.

1 Comment

That still creates a new String object. String objects are immutable and applying any manipulation function would result in the creation of a new String. So, you aren't really giving a performance boost.
1

Answered before the update:

I'm not an expert in regex, but hope this "\\d+" is useful to you. Invoke the below method with pattern: "\\d+".

public static int returnInt(String pattern,String inputString){
    Pattern intPattern = Pattern.compile(pattern);
    Matcher matcher = intPattern.matcher(inputString);
    matcher.find();
    String input = matcher.group();
    return Integer.parseInt(input);
}

5 Comments

This certainly won't be faster than a hardcoded substring operation. It might be equivalent if you mentioned that the Pattern and Matcher must be reused for optimal performance but as it stands it is orders of magnitude slower. And if the OP is worried that the code in the question "dynamically creates a new instance of string" then regex is certainly not the way to go.
hardcoded substring operation : But the position of the int is random as posted by OP!
"How to read a number from position = 1 to the end of the string" - I think that is the question. Where position can vary but is known.
The first line : Is it possible in Java to efficiently read an integer from random position of the string.
First, thank you all. I have updated my question to be clear. I always read from pos = 1.
0

Answered after the update:

String is a final object, you cannot edit it, so if you want to get some digit value from it, you have the 2 ways:

1. Use your code, that will work fine, but if you care about performance, try 2nd way.

2. Divide your string on digits and add them to get the result:

public static void main(String[] args) {
    String input = "(123456";

    if(input.charAt(0) == '(') {
        System.out.println(getDigit(input));
    }
}

private static int getDigit(String s) {
    int result = 0;
    int increase = 10;

    for(int i = 1; i < s.length(); i++) {
        int digit = Character.getNumericValue(s.charAt(i));
        result*=increase;
        result += digit;
    }

    return result;
}

Output:

123456

Comments

0

If you don't want to allocate a new String then you can use the code in this other SO answer:

int charArrayToInt(char[] data, int start, int end) throws NumberFormatException {
    int result = 0;
    for (int i = start; i < end; i++) {
        int digit = ((int)data[i] & 0xF);
        if ((digit < 0) || (digit > 9)) throw new NumberFormatException();
        result *= 10;
        result += digit;
    }
    return result;
}

You can call it with charArrayToInt(s.toCharArray(), 1, s.length())

4 Comments

Will not s.toCharArray() allocate a memory to create a char[] object? If it will, where is a performance boost comparing to s.substring(1)?
It will, yes. But it doesn't need to declare the whole enclosing String object. Also, have your ever looked at the code for Integer.parseInt? Because it's robust to input errors and can parse negative number etc it's very complex - this parsing code is much simpler.
@Nick a quick benchmark of 10,000,000 iterations shows that the charArrayToInt method is about twice the speed of the parseInt and substring method.
Oh, I appreciate your efforts. Thank you. However, I guess the accepted answer is even faster.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.