用C标记化字符串 [英] Tokenizing strings in C

查看:85
本文介绍了用C标记化字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力来标记使用空间作为分隔符为字符串,但它不工作。请问为什么它不工作,任何一个有建议?

编辑:采用标记化:

 的strtok(字符串,);

在code是像下面的

  PCH = strtok的(STR,);
而(PCH!= NULL)
{
  的printf(%S \\ n,PCH);
  PCH =的strtok(NULL,);
}


解决方案

做这样的:

 个char [256];
的strcpy(S,一二三);
字符*令牌= strtok的(S,);
而(令牌){
    的printf(令牌:%S \\ N标记);
    令牌= strtok的(NULL,);
}

请注意: strtok的修改字符串的tokenising,所以它不可能是一个为const char *

I have been trying to tokenize a string using SPACE as delimiter but it doesn't work. Does any one have suggestion on why it doesn't work?

Edit: tokenizing using:

strtok(string, " ");

The code is like the following

pch = strtok (str," ");
while (pch != NULL)
{
  printf ("%s\n",pch);
  pch = strtok (NULL, " ");
}

解决方案

Do it like this:

char s[256];
strcpy(s, "one two three");
char* token = strtok(s, " ");
while (token) {
    printf("token: %s\n", token);
    token = strtok(NULL, " ");
}

Note: strtok modifies the string its tokenising, so it cannot be a const char*.

这篇关于用C标记化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆