如何在 C 中通过
'&'
将字符串拆分为标记?
char *token;
char *state;
for (token = strtok_r(input, "&", &state);
token != NULL;
token = strtok_r(NULL, "&", &state))
{
...
}
strchr()
):
#include <string.h>
char *data = "this&&that&other";
char *next;
char *curr = data;
while ((next = strchr(curr, '&')) != NULL) {
/* process curr to next-1 */
curr = next + 1;
}
/* process the remaining string (the last token) */
strchr(const char *s, int c)
返回指向 c
中 s
的下一个位置的指针,如果在 NULL
中未找到 c
,则返回 s
。
你也许可以使用
strtok()
,但是,我不喜欢strtok()
,因为:
"a&&b&c"
,则返回的标记为 "a"
、"b"
和 "c"
。请注意,"a"
之后没有空标记。您可以使用 strok() 函数,如下例所示。
/// Function to parse a string in separate tokens
int parse_string(char pInputString[MAX_STRING_LENGTH],char *Delimiter,
char *pToken[MAX_TOKENS])
{
int i;
i = 0;
pToken[i] = strtok(pInputString, Delimiter);
i++;
while ((pToken[i] = strtok(NULL, Delimiter)) != NULL){
i++;
}
return i;
}
/// The array pTokens[] now contains the pointers to the start of each token in the (unchanged) original string.
sprintf(String,"Token1&Token2");
NrOfParameters = parse_string(String,"&",pTokens);
sprintf("%s, %s",pToken[0],pToken[1]);
对我来说,使用
strtok()
函数既不直观又太复杂,所以我设法创建了自己的函数。作为参数,它接受要分割的字符串、确定标记之间的空格的字符和表示找到的标记数量的指针(在循环中打印这些标记时很有用)。该函数的缺点是每个令牌的最大长度是固定的。
#include <stdlib.h>
#include <string.h>
#define MAX_WORD_LEN 32
char **txtspt(const char *text, char split_char, int *w_count)
{
if(strlen(text) <= 1)
return NULL;
char **cpy0 = NULL;
int i, j = 0, k = 0, words = 1;
//Words counting
for(i = 0; i < strlen(text); ++i)
{
if(text[i] == split_char && text[i + 1] != '\0')
{
++words;
}
}
//Memory reservation
cpy0 = (char **) malloc(strlen(text) * words);
for(i = 0; i < words; ++i)
{
cpy0[i] = (char *) malloc(MAX_WORD_LEN);
}
//Splitting
for(i = 0; i < strlen(text) + 1; ++i)
{
if(text[i] == split_char)
{
cpy0[k++][j] = '\0';
j = 0;
}
else
{
if(text[i] != '\n') //Helpful, when using fgets()
cpy0[k][j++] = text[i]; //function
}
}
*w_count = words;
return cpy0;
}
很简单:
char str[] = "&a&&b&c"; // a mutable string
for (char *cp = str; (cp = strtok(cp, "&")) != NULL; cp = NULL) {
/* do something with the token */
}
有一次对
strtok()
的调用,即分隔符字符串的一个实例,并且 cp
的范围仅在此循环内。
使用
strchr()
的建议不考虑多个分隔符。如果有建议的话可能会更好strcspn()
。并且,请注意,必须在循环完成后处理最后一个令牌。这不是一个伟大的设计...
strtok()
的优点是代币已在其当前位置被隔离。如果它们的地址保存在指针数组中,则可以重复使用它们,而无需一遍又一遍地隔离它们。