C标记化字符串
C Tokenize String
我试图通过分隔符标记字符串,同时保留分隔符。我尝试使用strtok(string, delimiters)
,但该函数没有保留分隔符。例如,如果我的字符串是:
"my name < is|John >hi"
当我看到符号"space", "<", ">"
时,我想进行拆分。
代币将是:
my, space, name, space, < , space, is, |, John, space, <, hi
起初,我尝试逐个字符地读取,直到看到一个分隔符。如果我没有看到一个符号,我会把read字符附加到它前面的字符串中。例如,字符串"hi|bye"。我会读"h",读下一个字符。它是一个"i",所以把它附加到"h"后面。读取下一个符号,它是一个分隔符,所以将"hi"放入数组,也将"|"放入数组。重复直到完成。我在做这件事时遇到了问题。
这是我不起作用的代码:
int main()
{
char *line = "command1 | command2 command3 > command4 < command5";
do_tokenize(line);
return 0;
}
void do_tokenize(char *line)
{
char *tokenized[100];
char token[100];
int tokenCounter = 0;
int tokenLength = 0;
int i;
int newToken = 1;
int tokenNum = 0;
for(i=0; line[i] !=' '; i++)
{
if(line[i] != ' ' && line[i] != '<' && line[i] != '>' && line[i] != '|')
{
token[tokenLength] = line[i];
tokenLength++;
newToken = 1;
}
else
{
if(newToken == 1)
{
token[tokenLength] = ' ';
tokenized[tokenNum] = token;
tokenLength = 0;
tokenNum++;
newToken = 0;
token[tokenLength] = line[i];
token[tokenLength+1] = ' ';
tokenized[tokenNum] = token;
tokenLength = 0;
tokenNum++;
}
else
{
token[tokenLength] = line[i];
token[tokenLength+1] = ' ';
tokenized[tokenNum] = token;
tokenLength = 0;
tokenNum++;
newToken = 0;
}
}//end else
}//end for
token[tokenLength] = ' ';
tokenized[tokenNum] = token;
tokenNum++;
//print is saying that all of tokenized[j] is the last token ie command5
int j=0;
for(j; j<tokenNum; j++)
printf("%sn", tokenized[j]);
}
当我试图打印出整个数组(标记化[j])时,它表示所有数组都只是最后一个标记"command5"
。这在C
中完成。
似乎希望标记化数组的元素指向"line"中的每个标记。代码将令牌的每个字符忠实地复制到字符数组"token"中。将整个令牌加载到"token"后,它将被零终止。
-
所有这些都很好;然而,下一步似乎是代码存在缺陷的地方。然后,标记化数组中的下一个ponter被设置为指向"token"。问题是"token"是您的工作存储,并且每个新的token都会重新构建"token"的内容。
-
最后,"tokenize"数组中所有受影响的指针都指向同一个位置;具体地说,它们都指向"token"
-
因此,当打印出"tokenize"数组时,它们都指向"token",并且token的内容是最后解析的token("Command5")。。。
这将是一个很好的程序,可以在调试器中运行,了解它的作用和出错原因。
如果您正在使用某种IDE(集成开发环境),那么您所要做的可能就是按下"进入"按钮。
如果您使用的是gcc,那么您可以通过在gcc命令中添加-g
来轻松地使用gdb:
$ gcc -g myprog.c -o myprog
$ gdb myprog
(gdb) start
Temporary breakpoint 1 at 0x4009d1
Starting program: myprog
Temporary breakpoint 1, 0x00000000004009d1 in main ()
(gdb) step
Single stepping until exit from function main,
which has no line number information.
...