Hello everyone,
I have a code that use function to find and remove all occurrences of a string within a string (substring pending) and return the number of removals: I need to remove "xyz" in "abdxyzdxyz" the result should be "abdd" and a return of 2 removed. I used the debuger step into, it keep shown that "Removals = o" and the sbstring value = "abd", missing one character of "d". I can't see if I missed something, can some one help me see what I did wrong please.
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
void Remove(int );
//string str1 = "abdxyzdxyz";
//string str2 = "xyz";
char* str1 = "abdxyzdxyz";
char* str2 = "xyz";
//current_length = str1.length();
int main()
{
char substring[4];
int prev_occurence = 0;
int removals = 0;
int removed_occurence=0;
for(int i=0; i < strlen(str1); i++)
{
if(i % strlen(str2) == 0)
{
if(prev_occurence == 0)
memcpy(&substring, &str1[prev_occurence], 3);
else
memcpy(&substring, &str1[prev_occurence], 3);
substring[3] = '\0';
cout << substring;
removed_occurence = prev_occurence;
prev_occurence = i;
if(strcmp(str2, substring) == 0)
//if(strcmp(str2,substring) == 0)
{
Remove(removed_occurence);
//Remove(prev_occurence - strlen(str2));
//removed_occurence = prev_occurence - strlen(str2);
removals++;
}
}
}
cout << "Removals = " << removals << endl;
getch();
return 0;
}
void Remove(int prev_occurence)
{
char another_string[50];
//current_length -= 3;
//another_string.copy(str1, str1.length());
memcpy(&another_string, &str1[prev_occurence], strlen(str1) - prev_occurence);
another_string[strlen(str1) - prev_occurence] = '\0';
memcpy(&str1[prev_occurence], another_string, strlen(another_string));
str1[prev_occurence + strlen(another_string) + 1] = '\0';
}:icon_sad: