cpp split string by space

To split a string in C++ by space, you can use the std::istringstream class along with the std::getline function. Here are the steps to achieve this:

  1. Include the necessary header files:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
  1. Define the string you want to split:
std::string input = "Hello World";
  1. Create an std::istringstream object and pass the input string to its constructor:
std::istringstream iss(input);
  1. Create a vector to store the split tokens:
std::vector<std::string> tokens;
  1. Iterate over the string using std::getline and a delimiter:
std::string token;
while (std::getline(iss, token, ' ')) {
    tokens.push_back(token);
}

Explanation:

  • Step 1: The necessary header files are included to use the required classes and functions.

  • Step 2: A string named input is defined with the value "Hello World". You can replace this string with your own input.

  • Step 3: An std::istringstream object named iss is created and the input string is passed to its constructor. This object will be used to iterate over the input string.

  • Step 4: An empty vector named tokens is created. This vector will store the split tokens.

  • Step 5: A while loop is used to iterate over the iss object. The std::getline function is used to extract tokens from the iss object using a space (' ') as the delimiter. Each token is then added to the tokens vector using the push_back function.

At the end of these steps, the tokens vector will contain each word from the input string as separate elements. You can access these elements using the index notation, for example, tokens[0] will give you the first word, tokens[1] will give you the second word, and so on.

Here is the complete code:

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

int main() {
    std::string input = "Hello World";
    std::istringstream iss(input);
    std::vector<std::string> tokens;

    std::string token;
    while (std::getline(iss, token, ' ')) {
        tokens.push_back(token);
    }

    // Accessing the split tokens
    for (const auto& t : tokens) {
        std::cout << t << std::endl;
    }

    return 0;
}

Running this code will output:

Hello
World

This demonstrates that the string "Hello World" has been successfully split into two separate words.