In the previous article, we have discussed about What is a Memory Leak in C++ ?. Let us learn how to remove Substring from a String in C++ Program.
Removing a Substring from a String in C++
In this article we will learn how to remove the substring form a string . Removing of substring can be done many ways . A simple way to remove the substring is given below .
In this method we will use a function called strtok() . It is present in the <string.h > library . This function tokenizes a string i.e. covert a string to series of substring. It splits the char array according to given delimiters.
Syntax- char * strtok(char array[], constant char *delimiters);
Program to remove a substring from a string :
Let’s see the below program to understand the concept well.
#include <bits/stdc++.h>
using namespace std;
int main()
{
// declaration of string as char. array .
char arr[] = "He is a boy and she is a girl";
string s= "is" ;
char *temp = strtok(arr , " ");
// continue printing tokens while one of the delimiters is present in str[] and selected substring is not equal to the tokens
cout<< "update sting is : " ;
while (temp != NULL)
{
if(temp!= s )
cout << temp << " ";
temp = strtok(NULL, " ");
}
return 0 ;
}
Output : Update sting is : He a boy and she a girl
While the original String was “He is a boy and she is a girl” and after removing a particular substring the updated string is “He a boy and she a girl”.