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:
-
std::stringstream ss(s);
- This line initializes a stringstreamss
object with the strings
. A stringstream object treats a string as a stream, thereby enabling us to perform input/output operations on the string. -
std::string item;
andstd::vector<std::string> splittedStrings;
- These lines define an empty string,item
, and an empty vectorsplittedStrings
of strings which will be used to store the split words. -
The while loop:
while (std::getline(ss, item, ' '))
- Thestd::getline
function is used in this loop to extract characters from the streamss
, store them initem
, and stop when it encounters an empty space (’ ’). The loop continues this until there are no further characters in the strings
. -
splittedStrings.push_back(item);
- Each split word from the string is then added to the back of the vectorsplittedStrings
. -
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.