提取第N
th 字段的一种方法(同时在调用后将字符串保持在原始状态)是使用以下getFld
函数。首先,必要的标题:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
现在函数本身,我希望记录得足够好:
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;
}
最后,还有一个测试程序:
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;
}
编译并运行后,我得到:
Field 0 is 'Hi'
Field 1 is 'my'
Field 2 is 'name'
Field 3 is 'is'
Field 4 is 'lacrosse1991'
现在,请记住,这strdup
不是标准 C,但是,如果您的实现没有它,您可以使用这个。您可能还想更改strdup
失败时的行为,因为当前案例无法与超出范围的字段区分开来。
但是,这个代码应该可以作为开始的基线。