简体   繁体   English

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

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

Here is the format of the file that is being read:这是正在读取的文件的格式:

type Extensions类型扩展

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

I am able to read each entry from the file.我能够从文件中读取每个条目。 Now I want to make a key-value pair where the output for the above entries would be like现在我想制作一个键值对,上面条目的输出就像
{nb: application/mathematica} {注意:应用程序/数学}
{ma:application/mathematica} {ma:application/mathematica}
and so on.等等。

this is my current code to simply read through the entries这是我当前的代码,用于简单地阅读条目

 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);
}

"How to split the a string into separate words in C, where the space is not constant?" “如何在C中将a字符串拆分为单独的单词,其中空格不是恒定的?”

A simple answer would be using strtok() (string.h library), but keep it mind that this function affects your initial string.一个简单的答案是使用 strtok()(string.h 库),但请记住此函数会影响您的初始字符串。 So, if you want to use it again, you should use an temporary variable equal to your initial string.所以,如果你想再次使用它,你应该使用一个等于你初始字符串的临时变量。

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

where, in place of delim you should place : " ".在哪里,代替 delim 你应该放置:“”。

Basically, strtok splits your string according to given delimiters.基本上, strtok 根据给定的分隔符拆分您的字符串。

Here, i let u an example of 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