Kebtiz Kebtiz - 2 months ago 10
C Question

break a string into 'first' and 'second'

I have read through countless

strtok
posts, even copied some directly in their entirety into a new
int main
, but I can't figure out how to create the functions
get_first
and
get_second
.

get_first("This is a sentence."); //returns "This"

get_rest("This is a sentence."); //returns "is"


This is what I have so far, I have had nothing but trouble with
strtok
, but I don't know what else to use.

#include <stdio.h>
#include <string.h>

char * get_first(char * string) {
string = strtok(string, " ");
return string;
}

char * get_second(char * string) {
string = strtok(string, " ");
string = strtok(NULL, " ");
return string;
}

int main(int argc, char * argv[]) {
char * test_string = "This is a sentence.";
char * first = get_first(test_string);
char * second = get_second(test_string);
printf("%s\n", first);
printf("%s\n", second);
}


Getting no faults compiling with gcc -g -Wall, but it always seg faults. I think I have tried every permutation of
char c[]
and
char * c
there is.

Answer

strtok changes the string. (but String literals are not allowed to change.)
So create a copy.

Do the following:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char * get_first(const char *string){
    char *clone = strdup(string);//create copy, strdup is non standard. malloc and copy.
    char *token = strtok(clone, " ");
    if(token)
        token = strdup(token);
    free(clone);
    return token;
}

char * get_second(const char *string) {
    char *clone = strdup(string);
    char *token = strtok(clone, " ");
    if(token && (token = strtok(NULL, " ")))
        token = strdup(token);
    free(clone);
    return token;
}

int main(void) {
    char * test_string = "This is a sentence.";
    char * first = get_first(test_string);
    char * second = get_second(test_string);
    printf("%s\n", first);
    printf("%s\n", second);
    free(first);
    free(second);
}