OneBite.Dev - Coding blog in a bite size

Split A String By Comma Sign In C++

Code snippet for how to Split A String By Comma Sign In C++ with sample and detail explanation

Splitting a string by a specific delimiter such as a comma is a common programming task. In this article, we will be taking a succinct look at how to efficiently achieve this task utilizing the C++ programming language.

Code snippet for splitting a string by a comma sign

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

std::vector<std::string> split(std::string str, char delimiter) {
    std::vector<std::string> result;
    std::stringstream ss(str);
    std::string temp;

    while (getline(ss, temp, delimiter)) {
        result.push_back(temp);
    }

    return result;
}

Calling the function can be as simple as:

int main() {
    std::string str = "apple,banana,grape,orange";
    std::vector<std::string> fruits = split(str, ',');

    for(std::string fruit : fruits) {
        std::cout << fruit << std::endl;
    }

    return 0;
}

Code Explanation for splitting a string by a comma sign

To begin with, the split function accepts two parameters: a std::string and a char. The string is the text you want to split, and the char is the delimiter used to split the string.

We then declare a std::stringstream object ss and initialize it with the string str. std::stringstream is a stream class to operate on strings. It essentially allows us to treat the string object as a stream, and we can perform input/output operations on it.

We also declare a std::vector<std::string> named result to hold the substrings after the split, and a std::string temp to hold the each substring during the split.

Then, we use a loop to go through the std::stringstream object with getline(ss, temp, delimiter). This function reads characters from ss and appends them into temp until the delimiter is found.

In each loop, we use push_back to add the substring temp into our result vector.

Finally, after the loop finishes executing, the function returns the vector result which contains all the substrings.

In the main function, we create a string str which holds a comma-separated list of fruit names. We then call the split function, passing str and the comma as the delimiter. The result is a vector of fruit names.

This is then looped over using a range-based for loop, printing each fruit name to the console.

c-plus-plus