Split string with delimiters in C

前端 未结 20 1440
你的背包
你的背包 2020-11-21 11:56

How do I write a function to split and return an array for a string with delimiters in the C programming language?

char* str = \"JAN,FEB,MAR,APR,MAY,JUN,JUL,         


        
20条回答
  •  面向向阳花
    2020-11-21 12:06

    If you are willing to use an external library, I can't recommend bstrlib enough. It takes a little extra setup, but is easier to use in the long run.

    For example, split the string below, one first creates a bstring with the bfromcstr() call. (A bstring is a wrapper around a char buffer). Next, split the string on commas, saving the result in a struct bstrList, which has fields qty and an array entry, which is an array of bstrings.

    bstrlib has many other functions to operate on bstrings

    Easy as pie...

    #include "bstrlib.h"
    #include 
    int main() {
      int i;
      char *tmp = "Hello,World,sak";
      bstring bstr = bfromcstr(tmp);
      struct bstrList *blist = bsplit(bstr, ',');
      printf("num %d\n", blist->qty);
      for(i=0;iqty;i++) {
        printf("%d: %s\n", i, bstr2cstr(blist->entry[i], '_'));
      }
    
    }
    

提交回复
热议问题