How does strtok() split the string into tokens in C?

前端 未结 15 2025
陌清茗
陌清茗 2020-11-22 14:48

Please explain to me the working of strtok() function. The manual says it breaks the string into tokens. I am unable to understand from the manual what it actua

15条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 15:34

    This is how i implemented strtok, Not that great but after working 2 hr on it finally got it worked. It does support multiple delimiters.

    #include "stdafx.h"
    #include 
    using namespace std;
    
    char* mystrtok(char str[],char filter[]) 
    {
        if(filter == NULL) {
            return str;
        }
        static char *ptr = str;
        static int flag = 0;
        if(flag == 1) {
            return NULL;
        }
        char* ptrReturn = ptr;
        for(int j = 0; ptr != '\0'; j++) {
            for(int i=0 ; filter[i] != '\0' ; i++) {
                if(ptr[j] == '\0') {
                    flag = 1;
                    return ptrReturn;
                }
                if( ptr[j] == filter[i]) {
                    ptr[j] = '\0';
                    ptr+=j+1;
                    return ptrReturn;
                }
            }
        }
        return NULL;
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        char str[200] = "This,is my,string.test";
        char *ppt = mystrtok(str,", .");
        while(ppt != NULL ) {
            cout<< ppt << endl;
            ppt = mystrtok(NULL,", ."); 
        }
        return 0;
    }
    

提交回复
热议问题