Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C split string into token by delimiter and save as variables

Tags:

c

I want to split a string into tokens and save data into variables. I have the following string:

John|Doe|Melbourne|6270|AU

I need to split it by | and every token keep as variable so I can use them in my program, like:

fname = "John"
lname = "Doe"
city = "Melbourne"
zip = "6270"
country = "AU"

tried this so far, I can access first token the rest I don't know how (besides a while loop that doesn't help me):

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

int main (void) {
char str[] = "John|Doe|Melbourne|6270|AU";

strtok(str, "|");

printf("%s\n", str);
return 0;
}
like image 750
bsteo Avatar asked Jun 13 '13 10:06

bsteo


3 Answers

    char fname[32], lname[32], city[32], zip[32], country[32];

    strcpy(fname, strtok(str , "|"));
    strcpy(lname, strtok(NULL, "|"));
    strcpy(city , strtok(NULL, "|"));
    strcpy(zip , strtok(NULL, "|"));
    strcpy(country, strtok(NULL, "|"));

    printf("%s\n", fname);
    printf("%s\n", lname);
    printf("%s\n", city);
    printf("%s\n", zip);
    printf("%s\n", country);
like image 198
BLUEPIXY Avatar answered Nov 15 '22 17:11

BLUEPIXY


If the format is constant, you can use sscanf():

char fname[32], lname[32], city[32], zip[16], country[8];

if(sscanf(str, "%31[^|]|%31[^|]|%31[^|]|%15[^|]%7s",
               fname, lname, city, zip, country) == 5)
{
}

This uses the %[] character set format specifier to grab "everything except a vertical bar". The width is included to prevent buffer overruns.

like image 6
unwind Avatar answered Nov 15 '22 17:11

unwind


just keep on calling strtok

char* name = strtok(str, "|");
char* surname = strtok(NULL, "|");
...
like image 4
AndersK Avatar answered Nov 15 '22 18:11

AndersK