Split function is frequently used but C++ doesn’t provide built-in functions.

Here is a sample implementation.

vector<int> split(string s) {
    vector<string> list;
    int offset = 0;
    string delimiter = ","
    size_t delimiter_size = delimiter.length();

    while(1) {
        int pos = s.find(delimiter, offset); // 1
            
        if (pos == string::npos) { // 2
            list.push_back(s.substr(offset)); // 3
            break;
        }
        
        list.push_back(s.substr(offset, pos - offset)); // 4
        offset = pos + delimiter_size; // 5
    }
}
  1. is to find the first delimiter and get the position from the offset.
  2. is to check whether the position is the end of the string or not.
  3. gets the substring of the last string element from the last delimiter position to the end of the string.
  4. gets substring from current offset to the delimiter position that we got in 1.
  5. advances offset by delimiter position plus delimiter length.

discussion