One way to extract the N
th field (whilst keeping the string in original condition after the call) is to use the following getFld
function. First, the requisite headers:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
Now the function itself, which I hope is documented well enough:
char *getFld (char *srchStr, char delim, int numFld) {
char *copyStr, *retStr, *tmpStrPtr, delims[2];
// Make a copy so as to not damage original.
if ((copyStr = strdup (srchStr)) == NULL) return NULL;
// Create delimiter string from character.
delims[0] = delim; delims[1] = '\0';
retStr = NULL;
// Start loop, extracting fields.
tmpStrPtr = strtok (copyStr, delims);
while (tmpStrPtr != NULL) {
// If this is the field we want, make a copy.
if (numFld == 0) retStr = strdup (tmpStrPtr);
// Get next field.
tmpStrPtr = strtok (NULL, delims);
numFld--;
}
// Clean up, return field copy (must be freed eventually) or NULL.
free (copyStr);
return retStr;
}
And, finally, a test program for it:
int main (void) {
int i = 0;
char str[] = "Hi:my:name:is:lacrosse1991";
char *fld;
while ((fld = getFld (str, ':', i)) != NULL) {
printf ("Field %d is '%s'\n", i, fld);
free (fld);
i++;
}
return 0;
}
Upon compiling and running this, I get:
Field 0 is 'Hi'
Field 1 is 'my'
Field 2 is 'name'
Field 3 is 'is'
Field 4 is 'lacrosse1991'
Now, keep in mind that strdup
is not standard C but, if your implementation doesn't have it, you can use this one. You may also want to change the behaviour on strdup
failure since the current case cannot be distinguished from an out of range field.
But, this code should be fine as a baseline to start with.