string split by space c++
To split a string by space in C++, you can use the std::istringstream
class along with a std::vector
to store the individual words. Here are the steps to split a string by space in C++:
- Include the necessary headers:
#include <iostream>
#include <sstream>
#include <vector>
- Declare a string variable to hold the input string:
std::string inputString = "Hello world! This is a sample string.";
- Declare a
std::istringstream
object and initialize it with the input string:
std::istringstream iss(inputString);
- Declare a
std::vector
to store the individual words:
std::vector<std::string> words;
- Loop through the string using
std::getline
and extract each word:
std::string word;
while (iss >> word) {
words.push_back(word);
}
Explanation:
- In step 1, we include the necessary headers iostream
, sstream
, and vector
for input/output, string stream, and vector respectively.
- In step 2, we declare a string variable inputString
and assign it a sample string.
- In step 3, we declare a std::istringstream
object iss
and initialize it with the inputString
. This allows us to treat the input string as a stream for extraction operations.
- In step 4, we declare a std::vector
named words
to store the individual words from the input string.
- In step 5, we use a while loop to extract each word from the input string using std::getline
and store it in the word
variable. The iss >> word
syntax extracts a single word from the stream iss
and returns true
as long as there are more words to be extracted. We then push each word into the words
vector using the push_back
function.
After executing these steps, the words
vector will contain all the individual words from the input string, split by space. You can then use this vector for further processing or display the individual words as needed.
Here is the complete code:
#include <iostream>
#include <sstream>
#include <vector>
int main() {
std::string inputString = "Hello world! This is a sample string.";
std::istringstream iss(inputString);
std::vector<std::string> words;
std::string word;
while (iss >> word) {
words.push_back(word);
}
// Display the individual words
for (const auto& word : words) {
std::cout << word << std::endl;
}
return 0;
}
Output:
Hello
world!
This
is
a
sample
string.
I hope this explanation helps! Let me know if you have any further questions.