简体   繁体   中英

Splitting strings in C using strtok

I am very confused about C strings.

I have an array of strings which has 18 elements: char user[18][50] , where each element has strings in the format of "XXXX:YYYY:ZZZZ"

But I only need the ZZZZs, and I want to store them in, say, char z[18][50] rather than char *z for consistency (also not really clear about char *)

So I'm using strtok to split the string

char *split;
char *temp;
for (i=0; i<18; i++){
  temp = user[i];
  split = strtok(temp, ":");

  //Wanna do something here
}

So I guess at each iteration split is a pointer that points to an array of string, elements being: XXXX and YYYY and ZZZZ separately.

How can I only get ZZZZs and store them into char z[18][50] ?

Then you'll call strtok twice again to get it,

for (i=0; i<18; i++){
  temp = user[i];
  split = strtok(temp, ":");
  split = strtok(NULL, ":");
  split = strtok(NULL, ":");
  // Now split is pointing to ZZZZ    

  //Wanna do something here
}

The rindex function is more suitable :

#include <stdio.h>
#include <string.h>
#include <strings.h>
int  main() {
    char *split;
    char buffer[256];
    char temp[] = "XXXX:YYYYY:ZZZZZ";
    split = rindex(temp, ':') + 1;
    strcpy(buffer, split);
    printf("%s\n", buffer);
    return 0;    

} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM