Search code examples
cstringintlong-integerstrtol

C get numeric value from part of string


My task is to get long numeric value from part of char[], where I have the index of its begining and ending. I am just learning C, so it is confusing to me which function works the best in my case..

Lets say im making function getNum():

static char words[100000]; //lets say this is string filled  with many num. values and other stuff.  

long getNum(int begin, int end){
 return (long){part of string starting at words[begin] and ending at words[end]}    
}

I would like to know the best method and easiest method to do this. Any other comments are much appreciated too.


Solution

  • We give the algorithm, you write the code. Agree?

    OK, so the logic should be

    1. create an array of chars based on the end-start+1 index range.
    2. do a memcpy() from the source to the new array fro the end-start size.
    3. null-terminate the array.
    4. use strtol() to convert the array to numeric value.