Split Comma Separated String In C++

Welcome!. In this tutorial, we will learn how to split a comma separated string in the C++ programming language.

We will split the comma-separated string by using two methods:-

  • By using strtok() function
  • By writing our logic

Further, to execute the code given below, we are using an online compiler. Please use an online compiler only to execute the given codes as it is updated to the latest standard of C++.

So, let’s start!

First method: Using strtok() function

strtok() splits a string according to a given delimiter. It is called in a loop to retrieve all tokens.

But it returns NULL if there are no tokens left.

Code:-

#include <bits/stdc++.h> 
using namespace std; 
  void splitSen(char str[]) 
{ 
    char *tok = strtok(str,","); 
    while (tok!=NULL) 
    { 
        printf("%s\n",tok); 
        tok=strtok(NULL,","); 
    } 
} 
int main() 
{ 
    char str[100]="1,2,3,4,5";
    splitSen(str); 
    return 0; 
}

We have created a function splitSen with one argument(char array) of type void. Subsequently, we have defined a new pointer variable tok.
So now we will iterate this tok from start to end and print each tok. Therefore, in our main function, we have passed str as the lone argument.

Second method: Using our logic

Check out the code given below:

#include <bits/stdc++.h> 
using namespace std; 
void splitSen(string str) 
{ 
   string w = ""; 
   for (auto rem : str) 
   { 
       if (rem==',') 
       { 
           cout<<w<<endl; 
           w=""; 
       } 
       else
       { 
           w=w+rem; 
       } 
   }  
   cout<<w<<endl; 
} 
int main() 
{ 
    char str[100]="1,2,3,4,5";
    splitSen(str);
    return 0; 
}

So in this method, we have again defined one function named splitSen with one argument str of type string and function of the type void.

Moreover, we have also defined one variable w which is equal to null. Now, we iterate from the beginning of the string to the end using rem.

During the iterations, if rem is equal to the delimiter(i.e. “,”) then we print w else we add w with w and rem respectively.

At last, we print w until the end of string after the scope of for loop ends.

Sample Input/Output:-

Output:-
1
2
3
4
5

We have come to the end of this post. I hope this post may have helped you.

Thank You And Have Fun Coding!

Before you go, please check these amazing posts also.

  1. Iterate through a String word by word with C++
  2. Multiple ways of splitting a string with C++

Leave a Reply

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