OneBite.Dev - Coding blog in a bite size

Split A String By Empty Space In C++

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

In the world of programming, string manipulation is a vital skill to have under your belt. Among these tasks, splitting a string into words or smaller substrings is often required, especially in a popular programming language such as C++. In this article, we will discuss an efficient way to split a string by empty space in C++.

Code snippet to Split a String By Empty Space In C++

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

std::vector<std::string> splitString(const std::string &s) {
    std::stringstream ss(s);
    std::string item;
    std::vector<std::string> splittedStrings;
    
    while (std::getline(ss, item, ' ')) {
        splittedStrings.push_back(item);
    }
    
    return splittedStrings;
}

Code Explanation for Splitting a String By Empty Space In C++

In the code provided above, the function splitString takes a constant string s and returns a vector that contains all the split words of s. To break it down in further detail, here’s a step-by-step guide of how the function operates:

  1. std::stringstream ss(s); - This line initializes a stringstream ss object with the string s. A stringstream object treats a string as a stream, thereby enabling us to perform input/output operations on the string.

  2. std::string item; and std::vector<std::string> splittedStrings; - These lines define an empty string, item, and an empty vector splittedStrings of strings which will be used to store the split words.

  3. The while loop: while (std::getline(ss, item, ' ')) - The std::getline function is used in this loop to extract characters from the stream ss, store them in item, and stop when it encounters an empty space (’ ’). The loop continues this until there are no further characters in the string s.

  4. splittedStrings.push_back(item); - Each split word from the string is then added to the back of the vector splittedStrings.

  5. return splittedStrings; - The function finally returns the vector which contains the split words.

Therefore, this method allows us efficient and clear splitting of a string into seperate words in C++, creating ease in string manipulation tasks. This way of splitting strings is efficient, flexible, and can be adapted for other delimiters as well.

c-plus-plus