How to split the strings in vc++?

后端 未结 6 1778
攒了一身酷
攒了一身酷 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:58

    First and foremost if available, I would always use boost::tokenizer for this kind of task (see and upvote the great answers below)

    Without access to boost, you have a couple of options:

    You can use C++ std::strings and parse them using a stringstream and getline (safest way)

    std::string str = "stack+overflow*newyork;";
    std::istringstream stream(str);
    std::string tok1;
    std::string tok2;
    std::string tok3;
    
    std::getline(stream, tok1, '+');
    std::getline(stream, tok2, '*');
    std::getline(stream, tok3, ';');
    
    std::cout << tok1 << "," << tok2 << "," << tok3 << std::endl
    

    Or you can use one of the strtok family of functions (see Naveen's answer for the unicode agnostic version; see xtofls comments below for warnings about thread safety), if you are comfortable with char pointers

    char str[30]; 
    strncpy(str, "stack+overflow*newyork;", 30);
    
    // point to the delimeters
    char* result1 = strtok(str, "+");
    char* result2 = strtok(str, "*");
    char* result3 = strtok(str, ";");
    
    // replace these with commas
    if (result1 != NULL)
    {
       *result1 = ',';
    }
    if (result2 != NULL)
    {
       *result2 = ',';
    }
    
    // output the result
    printf(str);
    

提交回复
热议问题