Search code examples
cpointersc-stringsstrtok

C: Splitting a string into two strings, and returning a 2 - element array


I am trying to write a method that takes a string and splits it into two strings based on a delimiter string, similar to .split in Java:

char * split(char *tosplit, char *culprit) { 

    char *couple[2] = {"", ""};

    int i = 0; 

    // Returns first token  
    char *token = strtok(tosplit, culprit);    


    while (token != NULL && i < 2) { 
        couple[i++] = token; 
        token = strtok(NULL, culprit); 
    } 

    return couple;
} 

But I keep getting the Warnings:

In function ‘split’:
warning: return from incompatible pointer type [-Wincompatible-pointer-types]
     return couple;
            ^~~~~~
warning: function returns address of local variable [-Wreturn-local-addr]

... and of course the method doesn't work as I hoped.

What am I doing wrong?

EDIT: I am also open to other ways of doing this besides using strtok().


Solution

  • I'd caution your use of strtok, it probably does not do what you want it to. If you think it does anything like a Java split, read the man page and then re-read it again seven times. It is literally tokenizing the string based on any of the values in delim.

    I think you are looking for something like this:

    #include <stdio.h>
    #include <string.h>
    
    char* split( char* s, char* delim ) {
      char* needle = strstr(s, delim);
    
      if (!needle)
        return NULL;
    
      needle[0] = 0;
      return needle + strlen(delim);
    }
    
    int main() {
      char s[] = "Fluffy furry Bunnies!";
      char* res = split(s, "furry ");
      printf("%s%s\n", s, res );
    }
    

    Which prints out "Fluffy Bunnies!".