strtok when process two strings at same time

前端 未结 1 1554
迷失自我
迷失自我 2020-12-21 04:47

New in C and pretty confused about how to deal with several strings at the same time using strtok, for a simply example, I want to use strtok to extract the number and compa

1条回答
  •  有刺的猬
    2020-12-21 05:37

    Do not use strtok(). The documentation will tell you strtok() is not reentrant (i.e. should not be used across threads), but perhaps less obvious is the fact that the reason it is not reentrant is because it uses an internal save variable to remember where it's got to. That means you also can't use two instances at once. Instead use strtok_r() or failing that strsep() might work.

    strtok_r() is just like strtok, save that you pass it a char ** (i.e. a pointer to char *) where it can save where it's got to.

    The GNU libc manual page gives a good example of using a nested strtok_r which is what you are trying to do:

       #include 
       #include 
       #include 
    
       int
       main(int argc, char *argv[])
       {
           char *str1, *str2, *token, *subtoken;
           char *saveptr1, *saveptr2;
           int j;
    
           if (argc != 4) {
               fprintf(stderr, "Usage: %s string delim subdelim\n",
                       argv[0]);
               exit(EXIT_FAILURE);
           }
    
           for (j = 1, str1 = argv[1]; ; j++, str1 = NULL) {
               token = strtok_r(str1, argv[2], &saveptr1);
               if (token == NULL)
                   break;
               printf("%d: %s\n", j, token);
    
               for (str2 = token; ; str2 = NULL) {
                   subtoken = strtok_r(str2, argv[3], &saveptr2);
                   if (subtoken == NULL)
                       break;
                   printf(" --> %s\n", subtoken);
               }
           }
    
           exit(EXIT_SUCCESS);
       }
    

    0 讨论(0)
提交回复
热议问题