Split string with delimiters in C

前端 未结 20 1441
你的背包
你的背包 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:07

    I think strsep is still the best tool for this:

    while ((token = strsep(&str, ","))) my_fn(token);
    

    That is literally one line that splits a string.

    The extra parentheses are a stylistic element to indicate that we're intentionally testing the result of an assignment, not an equality operator ==.

    For that pattern to work, token and str both have type char *. If you started with a string literal, then you'd want to make a copy of it first:

    // More general pattern:
    const char *my_str_literal = "JAN,FEB,MAR";
    char *token, *str, *tofree;
    
    tofree = str = strdup(my_str_literal);  // We own str's memory now.
    while ((token = strsep(&str, ","))) my_fn(token);
    free(tofree);
    

    If two delimiters appear together in str, you'll get a token value that's the empty string. The value of str is modified in that each delimiter encountered is overwritten with a zero byte - another good reason to copy the string being parsed first.

    In a comment, someone suggested that strtok is better than strsep because strtok is more portable. Ubuntu and Mac OS X have strsep; it's safe to guess that other unixy systems do as well. Windows lacks strsep, but it has strbrk which enables this short and sweet strsep replacement:

    char *strsep(char **stringp, const char *delim) {
      if (*stringp == NULL) { return NULL; }
      char *token_start = *stringp;
      *stringp = strpbrk(token_start, delim);
      if (*stringp) {
        **stringp = '\0';
        (*stringp)++;
      }
      return token_start;
    }
    

    Here is a good explanation of strsep vs strtok. The pros and cons may be judged subjectively; however, I think it's a telling sign that strsep was designed as a replacement for strtok.

提交回复
热议问题