Split a string


StringViews 1398

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

 

Translate »