Thursday, 17 March 2016

Can you write own method for parsing String to integer ?


Method for parsing String to integer

Steps

 1. Initialize result with 0
 2. For each character in string do this
     a. Calculate : result = result * 10
     b. Get the digit from the character ('0' is 48 ASCII (or 0x30), so just subtract that from the character ASCII code to get the digit)
     c. Add the digit to the result
 3. Return result

Sample code
int number = 0;  // Initialize the result
int start = 0; // where to start iterating  
boolean negative = false; // negative or not
switch (src.charAt(0)) {  
    case '-':  
        negative = true;  
        start = 1;  
        break;  
    case '+':  
        start = 1;  
        break;  
    // default: do nothing  


for (int i = start; i < src.length(); i++)  {  
    number = number * 10 + Character.digit(src.charAt(i), 10);  
}  

if (negative)  {  
    number = -number;  
}  

return number;

No comments:

Post a Comment

Note: only a member of this blog may post a comment.