diff --git a/Extract Int from string b/Extract Int from string index 6940a33..02f3141 100644 --- a/Extract Int from string +++ b/Extract Int from string @@ -48,4 +48,32 @@ int my_getnbr(char *str){ //function declared } +/* A while loop to calculate string length is useless, so i implemented the algorith right in the while loop */ + +int my_getnbr(char *str){ + int start_index = 0, int result=0, int multiplier=1, int end_index=0, int i =0; + while(str[i] != '\0'){ // map where the digits are in the string + i++; + if (str[i] >= 48 && str[i] <= 57){ + start_index = i; + end_index = start_index; + while(str[end_index] >= 48 && str[end_index] <= 57){ + ++end_index; + } + end_index = end_index-1; + break; + } + } + + for(int k = end_index; k >= start_index; k--){ // calculate the int + result = result + (str[k]-'0')*multiplier; + multiplier=multiplier*10; + } + + if(str[start_index-1] == 45){ // if it's negative => *-1 + result = result * (-1); + } + return result; +} +