How to split the strings in vc++?

后端 未结 6 1773
攒了一身酷
攒了一身酷 2021-01-24 03:10

I have a string \"stack+ovrflow*newyork;\" i have to split this stack,overflow,newyork

any idea??

6条回答
  •  后悔当初
    2021-01-24 03:53

    There is another way to split a string using c/c++ :

    First define a function to split a string:

    //pointers of the substrings, assume the number of fields will not be over 5
    char *fields[5];   
    //str: the string to splitted
    //splitter: the split charactor
    //return the real number of fields or 0 if any error exits
    int split(char* str, char *splitter)
    {
        if(NULL == str) 
        {
            return 0;
        }
    
        int cnt;
        fields[0] = str;
        for(cnt = 1; (fields[cnt] = strstr(fields[cnt - 1], splitter)) != NULL && 
                cnt < 5; cnt++)
        {
            *fields[cnt] = '\0';
            ++fields[cnt];
        }
        return cnt;
    }
    

    then you can use this function to split string as following:

    char* str = "stack+ovrflow*newyork;"
    split(str, "+");
    printf("%s\n", fields[0]); //print "stack"
    split(fields[1], "*");
    printf("%s\n", fields[0]); //print "ovrflow"
    split(fields[1], ";");
    printf("%s\n", fields[0]); //print "newyork"
    

    this way will be more efficient and reusable

提交回复
热议问题