How is the split function used in C++?

There is no built-in split function in C++, but there are other methods that can be used to achieve similar functionality. Here is one common implementation method:

#include <iostream>
#include <string>
#include <vector>
#include <sstream>

std::vector<std::string> split(const std::string& str, char delimiter) {
    std::vector<std::string> tokens;
    std::stringstream ss(str);
    std::string token;
    
    while (getline(ss, token, delimiter)) {
        tokens.push_back(token);
    }
    
    return tokens;
}

int main() {
    std::string str = "Hello,World,Split,Example";
    char delimiter = ',';
    
    std::vector<std::string> tokens = split(str, delimiter);
    
    for (const auto& token : tokens) {
        std::cout << token << std::endl;
    }
    
    return 0;
}

The above code defines a split function that takes a string and a delimiter as parameters, and returns a vector containing the split substrings. In the main function, we use a comma as the delimiter to split a string and print the results of the split.

The output is:

Hello
World
Split
Example

This is a basic implementation of the split function that you can modify and expand according to your needs.

bannerAds