C++ split string by line

后端 未结 5 1447
我在风中等你
我在风中等你 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:45

    This fairly inefficient way just loops through the string until it encounters an \n newline escape character. It then creates a substring and adds it to a vector.

    std::vector Loader::StringToLines(std::string string)
    {
        std::vector result;
        std::string temp;
        int markbegin = 0;
        int markend = 0;
    
        for (int i = 0; i < string.length(); ++i) {     
            if (string[i] == '\n') {
                markend = i;
                result.push_back(string.substr(markbegin, markend - markbegin));
                markbegin = (i + 1);
            }
        }
        return result;
    }
    

提交回复
热议问题