How to split a string to 2 strings in C

前端 未结 8 661
猫巷女王i
猫巷女王i 2020-11-28 04:29

I was wondering how you could take 1 string, split it into 2 with a delimiter, such as space, and assign the 2 parts to 2 separate strings. I\'ve tried using strtok()

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 05:15

    #include 
    
    char *token;
    char line[] = "SEVERAL WORDS";
    char *search = " ";
    
    
    // Token will point to "SEVERAL".
    token = strtok(line, search);
    
    
    // Token will point to "WORDS".
    token = strtok(NULL, search);
    

    Update

    Note that on some operating systems, strtok man page mentions:

    This interface is obsoleted by strsep(3).

    An example with strsep is shown below:

    char* token;
    char* string;
    char* tofree;
    
    string = strdup("abc,def,ghi");
    
    if (string != NULL) {
    
      tofree = string;
    
      while ((token = strsep(&string, ",")) != NULL)
      {
        printf("%s\n", token);
      }
    
      free(tofree);
    }
    

提交回复
热议问题