Convert comma separated string to vector in C++

Given a comma-separated string, we want to convert it to a vector in C++.

Example:

String: "Hey,there,Howare,You"

Vector elements: "Hey" "There" "Howare" "You"

First Approach:

In this approach, we traverse through the string and whenever we find a comma, push a new empty string to the vector. And if there is no comma, keep pushing the character to the last string of the vector. Below is the code implementation of it to understand it better.

#include<bits/stdc++.h>
using namespace std;

int main(){
    string s="Hey,there,Howare,You";
    vector<string>v;
    
    v.push_back("");
    for(int i=0;i<s.size();i++){
        int n=v.size();
        if(s[i]==',')v.push_back("");
        //if comma is found push a new empty string to the vector
        else v[n-1].push_back(s[i]); 
        //if no comma, keep pushing the char to the last stirng of the vector
    }

    for(auto&it:v)cout<<it<<" ";
    return 0;
}

 

The second approach (Two-pointer approach):

To convert the string to a vector, we have to separate the substrings of a given string whenever we find a comma. For that, we will use two pointer approach. To get the substring, we need two parameters: First the starting index, and second the length of the substring. So we will traverse the string with one of the pointers and whenever this pointer reaches the index of the comma we will separate the substring and push_back it to the vector. And now we will point our second pointer to the next index of the first one (because the first one points to the comma and we don’t want to include the comma in our substring). Let’s see the code implementation to understand it better.

#include<bits/stdc++.h>
using namespace std; 
int main(){ 
    string s="Hey,there,Howare,You"; // given string 
    vector<string>v; //vector to store substrings of given string 
    int i=0,j=0; 
    while(i<s.size() && j<s.size()){ 
        if(s[j]==','){ // j-i will be the length of substring 
            v.push_back(s.substr(i,j-i));
            i=j+1; 
        } 
        j++; 
    } 
    // to put last substring because there is no comma in the end of given string so it will not be inserted in loop 
    v.push_back(s.substr(i,j-i)); 
    for(auto&it:v)cout<<it<<" "; return 0; 
}

Time Complexity: O(n), where n is the size of the string.

Space Complexity: O(1) since no extra space is used. [Note: the vector used to output is given in the question itself which is not counted as extra space].

Leave a Reply

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