#include <stdio.h> #include <string.h> int main () { char s[]="ab-cd:ef;gh:i-jkl mnop;qrs -tu :vwx-y;z"; char *delimit=" -:"; char *p; printf("%s\n",strtok(s, delimit)); while ((p=strtok(NULL, delimit))) printf("%s\n",p); }output
ab cd ef;gh i jkl mnop;qrs tu vwx y;zexample2:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main (int argc, char *argv[]) { char *s=*(argv+1); char *s1; char *delimit=","; char *p; int dev_state[2]; strtok(s, delimit); s1=s; dev_state[0]=atoi(s1); p=strtok(NULL, delimit); dev_state[1]=atoi(p); printf("[0]=%d\n",dev_state[0]); printf("[1]=%d\n",dev_state[1]); }執行:
./test 12,31 [0]=12 [1]=31
example 3:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define ROW 8 #define COL 64 char **split(char *target_str, char *delimit) { char *s, *s1; char *ptr, **ptr2; int i=0; ptr =(char *)malloc(sizeof(char*) * COL); strncpy(ptr, target_str, COL); ptr2 =(char **)malloc(sizeof(char*) * ROW); for (i = 0; i <ROW; i++) { ptr2[i] =(char *)malloc(sizeof(char *) * COL); } s=strtok(ptr, delimit); for(i=0; s != NULL; i++) { strcpy(ptr2[i], s); s = strtok(NULL, delimit); } free(ptr); return ptr2; } int main (void) { //split("hello,123,world,789", ","); int i=0; char **str = split("hello,111", ","); printf("str[0]=%s\n", str[0]); printf("str[1]=%s\n", str[1]); for (i = 0; i <ROW; i++) free(str[i]); free(str); return 0; }
沒有留言:
張貼留言