Split a string

0
192
Split a string

Write a program to Split a given input string by any delimiter.

Example

a)  Input string : Tutorial-Cup
Output : Tutorial
Cup

b) Input string: C, C++, Java
Output: C
C++
Java

Time complexity : O(n)

Algorithm

Split string[] according to the given delimiters,

1. Traverse input_string.

2. Keep printing tokens while any delimiters present.

3. Return Null, when there are no more tokens.

C++ Program

#include <bits/stdc++.h>

using namespace std;
 
//Function to split a string 
int main()
{
    char str[] = "Tutorial-Cup";
    //Traverse string and print token 
    //till we find delimiter
    char *token = strtok(str, "-");
    while (token != NULL)
    {
        cout<<token<<endl;
        token = strtok(NULL, "-");
    }
    return 0;
}

Try It

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here