I wrote a function that will search a string with a substring. When the substring is found, it is replaced with another substring. The problem I have with my code is that it wont replace the substring unless it is in the beginning of the string. Here's the code and thanks for the help!
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int length(char str[])
{
int i=0;
while(str[i] != '\0')
{
i++;
}
return i;
}
int substring(char str1[], char str2[], char str3[])
{
int len = length(str1);
int len2 = length(str2);
int len3 = length(str3);
if(len2 != len3)
{
cout << "ERROR: The find and replace strings are of different length." << endl;
cout << "Please change the find and replace strings to the same length." << endl;
return false;
}
for (int i= 0; i <=9; i++)
{
for (int j = 0; j <= (str1[i] -1); j++)
{
if (str1[j] == str2[0])
{
bool found = true;
int k = 0;
while (k < (len2) and found==true)
{
if (str2[k] == str1[k])
k++;
else
found = false;
}
if (found == true)
{
char templine[10];
templine[i] = str1[i];
int temp=0;
for (int m = j; m <= (len2-1); m++ )
{
str1[m] = str3[temp];
temp++;
}
int temp2 = j+(len3);
int test = (length(templine)-1);
for (int n = (j+len2); n <= test; n++)
{
str1[temp2] = templine[n];
temp2++;
}
}
}
}
}
return 0;
}
int main ()
{
char array[]="stupid";
char array2[]="up";
char array3[]="hi";
substring(array, array2, array3);
cout << "array: " << array <<endl;
system("PAUSE");
return 0;
}