I really need help with this last part of my program. I need to find a string within a larger string and if found return the start location of the substring. From the directions:
Note that your string location starts from 0 and ends at length -1. If the string is not found, a value of -1 will be returned.
I’ve started and the following code compiles, I just want to know if this is actually correct. I don’t want to get in too over my head but I need some feedback from experts. Am I doing this right? Or at least am I going in the right direction?
const int MyString::Find(const MyString& other)
{
int start(0);
int counter(0);
int end = other.Size;
int count(0);
int end1 = Size;
int nfound = -1;
char* temp;
temp = new char[other.Size];
if(other.String[0] != '\0' && other.String[0] != ' ')
{
if(other.String[count] == String[counter])
{
start = counter;
for(int i = count; i < end-1;i++)
{
for(int j = counter; j < end1 -1; j++)
{
temp[j] = String[j];
}
}
if(other == temp)
{
return start;
}
else
return nfound;
}
else{
while(other.String[count] != String[counter])
{
counter++;
if(other.String[count] == String[counter])
{
start = counter;
for(int i = count; i < end-1;i++)
{
for(int j = counter; j < end1 -1; j++)
{
temp[j] = String[j];
}
}
if(other == temp)
{
return start;
}
else
return nfound;
}
}
}
}
else
{
return nfound;
}
}
This line is all right, though it wants a corresponding
deletestatement:However, I doubt that this line does what you want:
Assuming that
Mystring::String(which were more conventionally namedMystring::string, but let that pass) has the typechar *, the latter line copies no characters fromdata.Stringinto the buffer attemp. Instead, it loses the buffer, after whichtempis just a synonym for, and points to the selfsame memory as,data.String.