繁体   English   中英

如何在 C 中将字符串拆分为单独的单词,其中空格不是恒定的?

[英]How to split the a string into separate words in C, where the space is not constant?

这是正在读取的文件的格式:

类型扩展

应用程序/mathematica nb ma mb
应用程序/mp21 m21 mp21

我能够从文件中读取每个条目。 现在我想制作一个键值对,上面条目的输出就像
{注意:应用程序/数学}
{ma:application/mathematica}
等等。

这是我当前的代码,用于简单地阅读条目

 char buf[MAXBUF];
 while (fgets(buf, sizeof buf, ptr) != NULL)
    {
        if(buf[0] == '#' || buf[0] == '\n')
            continue;  // skip the rest of the loop and continue



        printf("%s\n", buf);
}

“如何在C中将a字符串拆分为单独的单词,其中空格不是恒定的?”

一个简单的答案是使用 strtok()(string.h 库),但请记住此函数会影响您的初始字符串。 所以,如果你想再次使用它,你应该使用一个等于你初始字符串的临时变量。

char *p = strtok(char *str, const char *delim)

在哪里,代替 delim 你应该放置:“”。

基本上, strtok 根据给定的分隔符拆分您的字符串。

在这里,我让你举一个 strtok 的例子:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM