Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Extract Int from string
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}