Thread: How exactly is strspn and strscpn used in spliting up a string here

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    May 2015
    Posts
    228

    How exactly is strspn and strscpn used in spliting up a string here

    So I found a bit of code over in stackoverflow that I found a bit difficult to understand. What it does is it splits a string based on a delimiter and then stores the rest in a pointer while returning the part that was split.

    Here it is

    Code:
    char *strtok_r(char *str, const char *delim, char **nextp)
    {
        char *ret = NULL;
    
    
        if (str == NULL)
        {
            str = *nextp;
        }
    
    
        str += strspn(str, delim); // This part I don't understand
    
    
        if (*str == '\0')
        {
            return NULL;
        }
    
    
        ret = str;
    
    
        str += strcspn(str, delim); // and this part
    
    
        if (*str)
        {
            *str++ = '\0';
        }
    
    
        *nextp = str;
    
    
        return ret;
    }
    what strspn does is returns the length of the initial portion of str1 containing only characters that appear in str2 and strcspn does the opposite. The function's return type is size_t and not something like char *. So how is it that at the end of this function it is able to get the delimited part of the string based on the length that it got from strspn and strscpn?
    Last edited by deathslice; 04-01-2016 at 08:56 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Spliting up a string of numbers.
    By UltimateCoder in forum C++ Programming
    Replies: 23
    Last Post: 01-26-2012, 02:32 AM
  2. Spliting in group of two
    By RisingACK in forum C Programming
    Replies: 6
    Last Post: 11-10-2010, 12:00 PM
  3. reading and spliting a string
    By nitinjainb in forum C++ Programming
    Replies: 5
    Last Post: 06-24-2004, 08:35 AM
  4. strspn()
    By JDMac in forum C Programming
    Replies: 4
    Last Post: 11-04-2002, 04:01 PM
  5. int StrSpn(char *str, int ch);
    By Krush in forum C Programming
    Replies: 5
    Last Post: 11-01-2002, 07:13 PM