Remove characters from the first string that are in the second string in C++
In this tutorial, we will learn to remove the characters from the string are in the second string in C++.
Algorithm:
- Firstly, there are two input strings.
- Now initialize input_index = 0 to keep track of each character of input-output string.
- Initialize result_index=0 to keep track of each character of resultant string.
- Now construct an array named countarr.
- Here we will use a boolean array instead of int array because we don’t need the count of it, we need to know if the character is present in the string or not.
- So it will return a boolean value.
- Now we will traverse to each character of the string. If the count array will return 0, then only return this character to the resultant string.
- The time complexity of this approach is O(a+b) where a is the length of the first input string and b is the length of the second input string.
For Example:
- First string= “greatachievement”
- second string=” ate”
- resultant string =” grchivmn”
You may also like:
How to remove or eliminate the extra spaces from a given string in C++
C++ program to remove characters from the first string that are in the second string
Hence, you can see the implementation below of the above approach.
#include<iostream> using namespace std; #define Number_Char 256 int *Countarr(char *first_string) { int *count = (int *)calloc(sizeof(int), Number_chars); int i; for (i = 0; *(first_string+i); i++) count[*(first_string+i)]++; return count; } char *removechar(char *first_string, char *second_string) { int *count =Countarr(second_string); int input_index = 0, result_index = 0; while (*(first_string + input_index)) { char temp = *(first_string + input_index); if (count[temp] == 0) { *(first_string + result_index) = *(first_string + input_index); result_index++; } input_index++; } *(first_string+result_index) = '\0'; return first_string; } int main() { char first_string[]= "greatachivement"; char second_string [] = "ate"; cout<< removechar(first_string, second_string)); return 0; }
OUTPUT EXPLANATION:
INPUT: first_string=" greatachievement" second_string=" ate" OUTPUT: "grchivmn"
Leave a Reply