What is the purpose of the split function in C++?

In C++, there is no built-in split function. However, you can implement your own split function to divide a string.

The purpose of the split function is to divide a string into multiple sub-strings, separating the original string based on a specified delimiter. It is commonly used for processing text files, CSV files, or manipulating string data.

Here is an example implementation of the split function:

#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::string token;
    std::istringstream tokenStream(str);
    while (std::getline(tokenStream, token, delimiter)) {
        tokens.push_back(token);
    }
    return tokens;
}

int main() {
    std::string str = "Hello World!";
    std::vector<std::string> parts = split(str, ' ');
    for (const auto& part : parts) {
        std::cout << part << std::endl;
    }
    return 0;
}

In the example above, we defined a split function that takes a string and a delimiter as parameters. We used std::istringstream to split the string into multiple sub-strings and store them in a vector container. Next, we can iterate through the vector and print each sub-string.

In the main function, we pass the string “Hello World!” to the split function and use a space as the separator. Finally, we output each sub-string.

The output will be:

Hello
World!

This is the basic function of the split function. You can customize it as needed to meet different splitting requirements.

bannerAds