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
- Create a string containing the input and an empty std::vector object to hold the result.
- Initialize an empty std::string called token.
- Use a for loop to iterate over each character in the input string.
- 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.
- 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 Complexity – O(N)
Frequently Asked:
- Get string array length in C++
- Convert a string to lowercase in C++
- Convert a string to uppercase in C++
- How to trim strings in C++ using Boost String Algorithm Library
- 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 :
is
: It is an object of istream class and tells the function about the stream from where to read the input from.str
: It is a string object, the input is stored in this object after being read from the stream.delim
: It is the delimitation character which tells the function to stop reading further input after reaching this character.
Algorithm
- Include the necessary header files: , , , and .
- Create a string containing the input and a std::stringstream object using the input string.
- Create an empty std::vector object to hold the result.
- Initialize an empty std::string called token.
- 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.
- Inside the loop, add the token to the vector using the push_back function.
- 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.