简体   繁体   中英

how to only get the terms in the bracket using strtok

My input is (2,3,4),(2,5,4) I only want to get 2 3 4 \n 2 5 4 as my output. can anyone help me with this?

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

int main() {
   char string[50] = "(2,3,4),(2,5,4)";
   // Extract the first token
   char * token = strtok(string, "()");
   // loop through the string to extract all other tokens
   while( token != NULL ) {
      printf( " %s\n", token ); //printing each token
      token = strtok(NULL, "()");
   }
   return 0;
}
``

I have implemented this with the standard strtok() not the non-standard strsep() mentioned in comment.

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

int main(void) {
    char input[] = "(2,3,4),(2,5,4)";
    char *tok = strtok(input, "( ,)" );
    for(int i = 0; i < 2; i++) {
        // each set
        for(int j = 0; j < 3; j++) {
            // break each set
            if(tok) {
                printf("%s ", tok);   //printing each token
                tok = strtok(NULL, "( ,)" );
            }
        }
        printf("\n");
    }
    return 0;
}

Program output

2 3 4 
2 5 4 

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