C++ split string by newline

  1. static const size_t npos = -1;The position used to identify non-existent
    nposis a constant, denoted size_tby the maximum value ( Maximum value for size_t). Many containers provide this thing, used to represent the non-existent location, the type is generally std::container_type::size_type.
  2. find()Finds the first substring equal to a given sequence of characters. The search begins with pos, that is, the found substring must not start at posa position before .
#include <string.h>
#include <cstring>
#include <iostream>
#include <list>
#include <vector>

using namespace std;

void splitStr(std::string src, std::string pattern,
              std::vector<std::string> &sList) {
    
    
    int pos2 = 0;
    cout << "src       " << src << endl;
    for (int i = 0; i < src.size();) {
    
    
        pos2 = src.find('\n', i);
        cout << "pos2        " << pos2;
        if (pos2 != std::string::npos) {
    
    
            std::string strT = src.substr(i, pos2 - i);
            cout << "    strT        " << strT << endl;
            sList.push_back(strT);
            i = pos2 + 1;
            continue;

        } else {
    
    
            sList.push_back(src.substr(i, src.size() - 1));
        }
        break;
    }
}

int main() {
    
    
    string str = "\n10000\n20000";
    string pattern = "\n";
    std::vector<std::string> sList;
    splitStr(str, pattern, sList);
    cout << "\nsize        " << sList.size() << endl;
    for (int i = 0; i < sList.size(); i++) {
    
    
        cout << "content         " << sList.at(i) << endl;
    }
    return 0;
}

output result

src       
10000
20000
pos2        0    strT        
pos2        6    strT        10000
pos2        -1
size        3
content         
content         10000
content         20000

Guess you like

Origin blog.csdn.net/MMTS_yang/article/details/128616664