The purpose of this program is to be given 2 strings, and then it looks for string 2 in string one, and returns the pointer of the first occurrence of string 2 in string 1.
ex:
string1: banana
string2: an
'an' (string2) make up the 2nd and 3rd characters of string1 as well as the 4th and the 5th, but since 2nd and 3rd are the first occurrence, then it looks for that. The program finds this and returns a pointer of where string2 is located in string one, in this case, the address of the 2nd character in string 1.
The code works perfectly, as long as string2 is NOT a constant in the function. The problem is that I have to keep it as a constant.
I even tried traveling-pointers as to not change the content of the string but that didn't work either.
#include <iostream>
usingnamespace std ;
char *strstr(char *str1, constchar *str2)
{
int count2= 0, count2_max= 0 ;
while (*(str2) != '\0') //recording max value of 2nd string
{
str2++ ;
count2_max++ ;
}
str2 -= count2_max ;
while (*(str1) != '\0') //checking string 1 character by character for if it has string 2 in it.
{
if (*(str2) == *(str1))
{
str2++ ;
count2++ ;
}
else
{
if (*(str1) != *(str1-1))
{
count2= 0 ;
}
}
if (count2 == count2_max) //checking if 2nd string is complete in the first string
{
str1=((str1-count2_max) + 1) ;
return str1 ;
}
str1++ ;
}
if (*(str1) == '\0')
{
return NULL ;
}
}
void main()
{
char *str1= newchar[100] ; //The first string
char *str2= newchar[100] ; //The second string
cout << "Please Enter the string: " ; cin.getline(str1, 100) ;
cout << "Now please enter the second string: " ; cin.getline(str2, 100) ;
cout << endl << "The pointer to the first occured second string (str2) in the first string (str1) holds the following address: " << (int*)strstr(str1, str2) << endl << endl ;
delete []str1 ;
delete []str2 ;
}
@miinipaa check it now. I added the const to the second parameter of the function and now it doesnt work. How can i make it work while keeping it constant ..??