简体   繁体   English

如何使用 strtok() 将包含空格的给定字符串拆分为多个字符串?

[英]How to use strtok() to split the given string containing spaces into multiple strings?

I have a file named email.txt, which contains some text.我有一个名为 email.txt 的文件,其中包含一些文本。 I am trying to split the given string containing spaces into multiple strings.我正在尝试将包含空格的给定字符串拆分为多个字符串。 The program I wrote does not split the words into separate lines.我编写的程序没有将单词分成单独的行。 It gives me the output of the last word of the file.它给了我文件最后一个字的 output。 Here is my code这是我的代码

#include <stdio.h>
#include <string.h>
#define MAXCHAR 1000
int main()
{
    FILE *fp2;    
    char str2[MAXCHAR];
    int line = 0;
    char delim[] = " ";
    int init_size = strlen(str2);
    fp2 = fopen("email.txt","r");
    while( fgets( str2, MAXCHAR, fp2 )) {
        line++;
        // printf(" %s",str2);  
    }
    char *ptr = strtok(str2, delim);
    
    while(ptr != NULL)
    {
        printf("%s\n", ptr);
        ptr = strtok(NULL, delim);
    }       
    
    return 0;
}

You are first looping over all the lines in your file, and then you loop over strtok() returns.首先遍历文件中的所有行,然后遍历strtok()返回。 This means you only ever tokenize the last line read.这意味着您只会标记最后一行读取的内容。

You need to nest those loops -- read a line, tokenize, then read the next line.您需要嵌套这些循环——读取一行,标记化,然后读取下一行。

while( fgets( str2, MAXCHAR, fp2 )) {
    char * ptr;
    line++;
    //  printf(" %s",str2);
    ptr = strtok(str2, delim);

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

You could just iterate over all the characters and then output either您可以遍历所有字符,然后遍历 output

  • the character you just read or您刚刚阅读的角色或
  • if the character is a space, a newline character如果字符是空格,则为换行符

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

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