有许多方法可以将字符串拆分为用空格分隔它们的标记。诀窍是让它尽可能高效和合理地健壮,而不会过度复杂化。两种基本方法是使用(1)“英寸蠕虫”方法(简单地使用 2 个指针,一个开始和结束指针,一次处理一个字符的字符串,或者(2)使用其中一个libc 提供的标记函数(例如strtok 或strsep)。
使用 inch-worm 方法,您拥有完全的控制权和竞争灵活性,但是在您向下处理字符串时,由 您 跟踪每个指针指向的位置。 (熟悉这种方法的一个好方法是在 paper 上编写您要解析的字符串,并根据需要手动推进指针 - 随时编写您的例程)。一个例子:
char *string = test->myString; //holds the whole string
char *p = string;
while (*p) /* while not end of string */
{
char *sp = p; /* set a start pointer */
while (*p && *p != ' ') p++; /* advance to space */
char *output_token = malloc (p - sp + 1); /* allocate */
strncpy (output_token, sp, p - sp); /* copy */
output_token[p - sp] = 0; /* force null-termination */
printf(" %s\n", output_token);
free (output_token); /* free if not needed */
while (*p && *p == ' ') p++; /* find next non-space */
}
第二种方法使用strtok 来做基本相同的事情。 注意:您可以随意在分隔符字符串中放置任意数量的字符,并且对于strtok 的每次调用,它们不要求使用相同的字符。这可以提供很大的灵活性。一个例子:
char *string = test->myString; //holds the whole string
char *p = string; /* pointer to string */
char *tok = NULL; /* pointer to token */
for (tok = strtok (p, " "); tok; tok = strtok (NULL, " \n"))
{
char *output_token = strdup (tok); /* allocate & copy at once */
printf(" %s\n", output_token);
free (output_token);
}
如果您想通过一个示例来比较两者,一个简短的示例可能如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char **argv) {
// char *string = test->myString; //holds the whole string
char *string = argc > 1 ? argv[1]: "some string with spaces";
printf ("\n With pointer arithmetic:\n\n");
char *p = string;
while (*p) /* while not end of string */
{
char *sp = p; /* set a start pointer */
while (*p && *p != ' ') p++; /* advance to space */
char *output_token = malloc (p - sp + 1); /* allocate */
strncpy (output_token, sp, p - sp); /* copy */
output_token[p - sp] = 0; /* force null-termination */
printf(" %s\n", output_token);
free (output_token); /* free if not needed */
while (*p && *p == ' ') p++; /* find next non-space */
}
printf ("\n With strtok:\n\n");
p = string;
char *tok = NULL; /* pointer to each token in string */
/* using strtok to separate string into tokens at spaces */
for (tok = strtok (p, " "); tok; tok = strtok (NULL, " \n"))
{
char *output_token = strdup (tok);
printf(" %s\n", output_token);
free (output_token);
}
return 0;
}
示例/输出
$ ./bin/charbufsplit "This is a longer string with many more spaces"
With pointer arithmetic:
This
is
a
longer
string
with
many
more
spaces
With strtok:
This
is
a
longer
string
with
many
more
spaces