簡體   English   中英

如何使用 strtok 僅獲取括號中的術語

[英]how to only get the terms in the bracket using strtok

我的輸入是(2,3,4),(2,5,4)我只想得到2 3 4 \n 2 5 4作為我的 output。 誰能幫我這個?

#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;
}
``

我已經使用標准strtok()而不是評論中提到的非標准strsep()實現了這一點。

#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;
}

程序 output

2 3 4 
2 5 4 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM