C++ split string by line

后端 未结 5 1465
我在风中等你
我在风中等你 2020-12-08 07:25

I need to split string by line. I used to do in the following way:

int doSegment(char *sentence, int segNum)
{
assert(pSegmenter != NULL);
Logger &log =          


        
5条回答
  •  难免孤独
    2020-12-08 07:35

    You can call std::string::find in a loop and the use std::string::substr.

    std::vector split_string(const std::string& str,
                                          const std::string& delimiter)
    {
        std::vector strings;
    
        std::string::size_type pos = 0;
        std::string::size_type prev = 0;
        while ((pos = str.find(delimiter, prev)) != std::string::npos)
        {
            strings.push_back(str.substr(prev, pos - prev));
            prev = pos + 1;
        }
    
        // To get the last substring (or only, if delimiter is not found)
        strings.push_back(str.substr(prev));
    
        return strings;
    }
    

    See example here.

提交回复
热议问题