Splitting a string by some delimiter is a very common task in programmers day to day life.

For example, we have an email address, and we want to extract email host which is part after @ in email address, example@gmail.com. After splitting this email address by “@”, there will be two strings “example”, “gmail.com”.

Use case of string splitting contains, tokenizing things in compilers, extracting relevant data with Web crawlers etc.

String splitting logo

Code

#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;  
}
big_string = "codeincafeinweb"
big_string.split("in")
for s in big_string:
    print(s)

Output of these program is (Same for both)

code
cafe
web

output

Thanks for being here.
Happy Coding, bye 👋