How To Split Strings In C++

This topic will discuss how we can split given strings into a single word in the C++ programming language . When we divide a group of words or string collections into single words, it is termed the split or division of the string. However, splitting strings is only possible with some delimiters like white space , comma (,), a hyphen (-), etc., making the words an individual. Furthermore, there is no predefined split function to divide the collection of strings into an individual string. So, here we will learn the different methods to split strings into a single one in C++.

Different method to achieve the splitting of strings in C++

  • Use strtok function to split strings
  • Use custom split function to split strings
  • Use std::getline function to split string
  • Use find and substr function to split string
  • Use strtok function to split strings

strtok: A strtok function is used to split the original string into pieces or tokens based on the delimiter passed.

Syntax

Example

char *ptr = strtok( str, delim)

In the above syntax, a strtok has two parameters, the str , and the delim .

str : A str is an original string from which strtok function split strings.

delim : It is a character that is used to split a string. For example, comma (,), space , hyphen (-), etc.

Return : It returns a pointer that references the next character tokens. Initially, icpp tutorials to the first token of the strings.

Note: A strtok function modifies the original string and puts a NULL character ('\0') on the delimiter position on each call of the strtok function. In this way, it can easily track the status of the token.

Program to split strings using strtok function

Let's consider an example to split string in C++ using strtok function.

Program.cpp

Example

#include <iostream>

#include <cstring>

using namespace std;

int main()

{

	char str[100]; // declare the size of string	

	cout << " Enter a string: " <<endl;

	cin.getline(str, 100); // use getline() function to read a string from input stream

	

	char *ptr; // declare a ptr pointer

	ptr = strtok(str, " , "); // use strtok() function to separate string using comma (,) delimiter.

	cout << " \n Split string using strtok() function: " << endl;

	// use while loop to check ptr is not null

	while (ptr != NULL)

	{

		cout << ptr  << endl; // print the string token

		ptr = strtok (NULL, " , ");

	}

	return 0;

}

Output

Output

Enter a string:

Learn how to split a string in C++ using the strtok() function.

 Split string using strtok() function:

Learn

how

to

split

a

string

in

C++

Using

the

strtok()

function.

Program to use custom split function to split strings

Let's write a program to split sequences of strings in C++ using a custom split function.

Program2.cpp

Example

#include <iostream>

#include <string>

#define max 8 // define the max string

using namespace std;

string strings[max]; // define max string

// length of the string

int len(string str)

{

	int length = 0;

	for (int i = 0; str[i] != '\0'; i++)

	{

		length++;

		

	}

	return length;   

}

// create custom split() function

void split (string str, char seperator)

{

	int currIndex = 0, i = 0;

	int startIndex = 0, endIndex = 0;

	while (i <= len(str))

	{

		if (str[i] == seperator || i == len(str))

		{

			endIndex = i;

			string subStr = "";

			subStr.append(str, startIndex, endIndex - startIndex);

			strings[currIndex] = subStr;

			currIndex += 1;

			startIndex = endIndex + 1;

		}

		i++;

		}	

}

int main()

{

	string str = "Program to split strings using custom split function.";

	char seperator = ' '; // space

	split(str, seperator);

	cout <<" The split string is: ";

	for (int i = 0; i < max; i++)

	{

		cout << "\n i : " << i << " " << strings[i];

	}

	return 0;

}

Output

Output

The split string is:

 i : 0 Program

 i : 1 to

 i : 2 split

 i : 3 strings

 i : 4 using

 i : 5 custom

 i : 6 split

 i : 7 function.

Use std::getline function to split string

A getline function is a standard library function of C++ used to read the string from an input stream and put them into the vector string until delimiter characters are found. We can use std::getline function by importing the <string> header file.

Syntax

Example

getline(str, token, delim);

It has three parameters:

str: A str is a variable that stores original string.

token: It stores the string tokens extracted from original string.

delim: It is a character that are used to split the string. For example, comma (,), space , hyphen (-), etc.

Program to use getline function to split strings

Let's consider an example to split strings using the getline function in C++.

Program3.cpp

Example

#include <iostream>

#include <string>

#include <vector>

#include <sstream>

using namespace std;

 

int main()

{

    string S, T;  // declare string variables

 

    getline(cin, S); // use getline() function to read a line of string and store into S variable.

 

    stringstream X(S); // X is an object of stringstream that references the S string

 

 	// use while loop to check the getline() function condition

    while (getline(X, T, ' ')) {

    	/* X represents to read the string from stringstream, T use for store the token string and,

		 ' ' whitespace represents to split the string where whitespace is found. */

    	

        cout << T << endl; // print split string

    }

 

    return 0;

}

Output

Output

Welcome to the Cpp Tutorial and Learn C++ Programming Language.

Welcome

to

the

Cpp Tutorial

and

Learn

C++

Programming

Language.

Program to split the given string using the getline function

Let's consider an example to split a given string in C++ using the getline function.

Program4.cpp

Example

#include <iostream>

#include <string>

#include <vector>

#include <sstream>

void split_str( std::string const &str, const char delim,

		std::vector <std::string> &out )

		{

			// create a stream from the string

			std::stringstream s(str);

			

			std::string s2;

			while (std:: getline (s, s2, delim) )

			{

				out.push_back(s2); // store the string in s2

			}

		}

		

		int main()

		{

			std:: string s2 = "Learn How to split a string in C++";

			const char delim = ' '; /* define the delimiter like space (' '), comma (,), hyphen (-), etc. */

			

			std::cout << "Your given string is: " << s2;  

			std::vector <std::string> out; // store the string in vector

			split_str (s2, delim, out); // call function to split the string

			

			// use range based for loop

			for (const auto &s2: out)

			{

				std::cout << "\n" << s2;

			}

			return 0;

		}

Output

Output

Your given string is: Learn How to split a string in C++

Learn

How

to

split

a

string

in

C++

Use find and substr function to split strings

Let's write a program to use find function and substr function to split given strings in C++.

Program4.cpp

Example

#include <iostream>

#include <string>

using namespace std;

int main()

{

// given string with delimiter

string given_str = "How_to_split_a_string_using_find()_and_substr()_function_in_C++";

string delim = "_"; // delimiter

cout << " Your string with delimiter is: " << given_str << endl;

size_t pos = 0;

string token1; // define a string variable

// use find() function to get the position of the delimiters

while (( pos = given_str.find (delim)) != std::string::npos)

{

token1 = given_str.substr(0, pos); // store the substring 

cout << token1 << endl;

given_str.erase(0, pos + delim.length());  /* erase() function store the current positon and move to next token. */ 

}

cout << given_str << endl; // it print last token of the string.

}

Output

Output

Your string with delimiter is: How_to_split_a_string_using_find()_and_substr()_function_in_C++

How

to

split

a

string

using

find()

and

substr()

function

in

C++

In the above program, we use a find function inside the loop to repeatedly find the occurrence of the delimiter in the given string and then split it into tokens when the delimiter occurs. And the substr function stores the sub-string to be printed. On the other hand, an erase function stores the current position of the string and moves to the next token, and this process continues until we have got all the split strings.

Input Required

This code uses input(). Please provide values below: