How to Split a String into a vector in C++?

In this article, we will discuss different ways to slit a string into a vector in C++.

Table Of Contents

Method 1: Using a loop

One way to split a string is to use a delimiter, such as a space or a comma, to separate the elements in the string. Here we use a for loop to split a string into a vector in C++

Algorithm

  1. Create a string containing the input and an empty std::vector object to hold the result.
  2. Initialize an empty std::string called token.
  3. Use a for loop to iterate over each character in the input string.
  4. Inside the loop, check if the current character is the delimiter. If it is, add the token to the vector using the push_back function and clear the token string. If it is not the delimiter, append the character to the token string.
  5. After the loop, add the last token to the vector.

Program

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

using namespace std;

int main() {

    string str = "apple,banana,orange";

    vector<string> vec;

    string token;
    size_t i = 0;

    for (; i < str.size(); i++) {
        if (str[i] == ',') {
            // found the delimiter, add the token to the vector
            vec.push_back(token);
            token.clear();
        } else {
            // not the delimiter, append the character to the token
            token += str[i];
        }
    }

    vec.push_back(token);

    // print the result
    for (const auto& s : vec) {
        cout << s << '\n';
    }

    return 0;
}

Output

apple
banana
orange

Time ComplexityO(N)

  • N is the length of the input string.
    This is because the for loop iterates over each character in the input string once and performs a constant amount of work for each iteration.

Method 2: Using std::stringstream

Another way to split a string is to use the stringstream class. To do this, you can use the std::istringstream class to read the string and the std::getline function to split the string based on the delimiter provided.

getline()

Syntax :

istream& getline(istream& is, string& str, char delim);

Parameters :

  1. is: It is an object of istream class and tells the function about the stream from where to read the input from.
  2. str: It is a string object, the input is stored in this object after being read from the stream.
  3. delim: It is the delimitation character which tells the function to stop reading further input after reaching this character.

Algorithm

  1. Include the necessary header files: , , , and .
  2. Create a string containing the input and a std::stringstream object using the input string.
  3. Create an empty std::vector object to hold the result.
  4. Initialize an empty std::string called token.
  5. Use a while loop and the std::getline function to split the stringstream into tokens using the delimiter ‘,’. The std::getline function reads characters from the stringstream until it encounters the delimiter or the end of the stringstream. It stores the characters in the token string and returns true if it successfully reads a token. The loop continues as long as std::getline returns true.
  6. Inside the loop, add the token to the vector using the push_back function.
  7. After the loop, iterate over the vector and print each element.

Program

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

using namespace std;

int main() {
    // input string
    string str = "apple,banana,orange";

    // create a stringstream from the input string
    stringstream ss(str);

    // create a vector to hold the result
    vector<string> vec;

    // split the string using the delimiter ','
    string token;
    while (getline(ss, token, ',')) {
        vec.push_back(token);
    }

    // print the result
    for (const auto& s : vec) {
        cout << s << '\n';
    }

    return 0;
}

Output

apple
banana
orange

Time Complexity – O(N)

  • N is the length of the input string.

This is because the while loop iterates over each character in the input string once and performs a constant amount of work for each iteration.
The std::getline function has a time complexity of O(m), where m is the length of the extracted token. However, since the loop terminates when std::getline() encounters the delimiter or the end of the stringstream, the overall time complexity of the loop is O(n).

Method 2: Using strtok()

The strtok() function is a C function that is used to split a string into tokens. It takes two arguments: a string to be split, and a string containing one or more characters that are used to split the string. The function returns a pointer to the next token in the string, or nullptr if there are no more tokens.

Program

#include <iostream>
#include <cstring>
#include <vector>

using namespace std;

int main() 
{
    // The string to be split
    char s[] = "hello world this is a test";

    vector<string> vec;

    // Split the string using strtok
    char* token = strtok(s, " ");
    while (token != nullptr)
    {
        vec.push_back(string(token));
        token = strtok(nullptr, " ");
    }

    for(auto substr: vec)
    {
        cout<< substr <<endl;
    }
    return 0;
}

Output

hello
world
this
is
a
test

Time Complexity – O(N)

N is the length of the string.
This is because the strtok function processes the string only once.

Note

strtok() can only handle single-character delimiters, so if you have multi-character delimiters inside the string to split, you will need to use a different method mentioned above. Also, the strtok function modifies the original string, so it is not a good choice if you want to preserve the original string.

Summary

In this article, we learned how to split a string into a vector using a for loop, stringstream class and strtok function. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top