dol: initial dol commit
[jump.git] / dol / src / dol / visitor / hdsd / lib / dol.c
1 #include "dol.h"
2
3 /**
4  * Gets an index of a string, where the index must be separated by
5  * a character specified in tokens.
6  * Returns -1, when an error occurs.
7  *
8  * Example:
9  * getIndex("name_1_2", "_", 0) will return 1.
10  * getIndex("name_1_2", "_", 1) will return 2.
11  *
12  * @param string string to parse
13  * @param tokens delimiter of indices
14  * @param indexNumber position of index (starting at 0)
15  */
16 int getIndex(const char* string, char* tokens, int indexNumber) {
17   char* string_copy;
18   char* token_pointer;
19   int index = 0;
20
21   string_copy = (char*) malloc(sizeof(char) * (strlen(string) + 1));
22   if (!string_copy) {
23     fprintf(stderr, "getIndex(): could not allocate memory.\n");
24     return -1;
25   }
26
27   strcpy(string_copy, string);
28
29   token_pointer = strtok(string_copy, tokens);
30   do {
31     token_pointer = strtok(NULL, tokens);
32     index++;
33   } while (index <= indexNumber && token_pointer != 0);
34
35   if (token_pointer) {
36     index = atoi(token_pointer);
37     free(string_copy);
38     return index;
39   }
40
41   return -1;
42 }