String Splitting in C++ (using find and substr)

String Splitting in C++

Hello guys,

you all have known the string splitting. Basically, string splitting is nothing but dividing the string based on a Delimiter or special character. 
For example, example@gmail.com by the delimiter looks like [example,gmail.com] 

use of string splitting is very broad as we can use this to tokenize thing in the web crawlers, data analysis in the data to extract useful things etc.

image logo

without wasting much time let's start splitting.

First of all create a schema for the c++ file.

#include <iostream>
#include <string>

using namespace std;
int main() {

return 0;
}

Now let's take a string that is to be split.
I took "codeincafeinweb".

take a delimiter, for example, I took "in".

and one more string variable for tokens.
string.find() method returns the starting position of the delimiter, if it founds nothing then it will return -1.
That is why we are using the while with terminating condition of -1.


string name = "codeincafeinweb";
// delimiter by which string is splitted
string delimiter = "in";
int pos;
string token = "";
// find method returns -1 if nothing found like the delimiter.
pos = name.find(delimiter);

now apply a while loop to check that we have found the delimiter every time or not, if not then exit out of the loop and last string, now or original string has the last part of the splitted string, that's why we are showing that last time.


while(pos != -1) {
// this gives the substring from the requested position
token = name.substr(0, pos);
// printing the splitted string
cout << token << endl;
name.erase(0, pos + delimiter.length());
pos = name.find(delimiter);
}
token = name;
cout << token;

That's it for the program.

Let's put the whole program into a single piece.


#include <iostream>
#include <string>

using namespace std;

int main() {
// string to be splitted
string name = "codeincafeinweb";
// delimiter by which string is splitted
string delimiter = "in";
int pos;
string token = "";
// find method returns -1 if nothing found like the delimiter.
pos = name.find(delimiter);
while(pos != -1) {
// this gives the substring from the requested position
token = name.substr(0, pos);
// printing the splitted string
cout << token << endl;
name.erase(0, pos + delimiter.length());
pos = name.find(delimiter);
}
token = name;
cout << token;
return 0;
}

sample run and output for this program is 


output

thanks for being here.
if you liked this post kindly share this post with your friends.

For more tips and programming tutorials stay tuned and subscribe to our blog.

Comments

Popular posts from this blog

C/C++ program to check the Palindrome string.

Second Equation of motion, How to implement using C language

Third Equation of motion, How to implement using C language