Split A String By A Delimiter In C++
Code snippet for how to Split A String By A Delimiter In C++ with sample and detail explanation
In the world of programming, there are several operations that need to be performed on strings in order to manipulate or analyze them. One such common operation is splitting a string by a delimiter. In this article, we will discuss how to split a string by a delimiter in C++.
Code Snippet: Splitting a String by a Delimiter in C++
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
std::string sentence = "This is a sentence";
char delimiter = ' ';
std::istringstream iss(sentence);
std::vector<std::string> words(std::istream_iterator<std::string>{iss},
std::istream_iterator<std::string>{});
for(auto word : words) {
std::cout << word << std::endl;
}
Code Explanation: Splitting a String by a Delimiter in C++
What this code does is it takes a string, applies a delimiter, and splits the string into smaller strings based on where the delimiter is found.
The first four lines are about including the necessary libraries.
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
Then, we declare a sentence we want to split and the delimiter we want to split by (in this case, a space).
std::string sentence = "This is a sentence";
char delimiter = ' ';
After this, we are using the istringstream
class from the <sstream>
library to perform operations on the string where we would split the sentence.
std::istringstream iss(sentence);
Next, using the istream_iterator
class from the <iterator>
library, we put the split words into a vector. The istream_iterator
class allows the input string to be treated as a stream, and it can then iterate over the string word by word.
std::vector<std::string> words(std::istream_iterator<std::string>{iss},
std::istream_iterator<std::string>{});
Lastly, we use a for-loop to iterate over the vector, which contains the split string, and print each word on a new line.
for(auto word : words) {
std::cout << word << std::endl;
}
When run, this code will output each word in the sentence on a new line. Overall, this is a simple and efficient way of splitting a string by a delimiter in C++.