I'm trying to write code that does the same thing as "strstr". However its just doing the same thing as "strchr". Anything I should look at to make it so when it runs "char my_strstr" it will look at the whole input instead of just the first letter?
/*
*/
#include <iostream>
using std::endl;
using std::cout;
using std::cin;
int my_strlen(char *str)
{
int count = 0;
while (*str != 0)
{
str++;
count++;
}
return count;
}
char *my_strstr(char *str, char *oldline)
{
while (*str != *oldline)
{
str++;
}
return str;
}
char * my_strchr(char *str, char character)
{
while (*str != character)
{
str++;
}
return str;
}
int main()
{
char lookfor,
line[100],
string[100],
change[100];
// String Length
cout << "Enter a line of text: ";
cin.getline(line, sizeof(line));
cout << "There are " << my_strlen(line) << " characters in: " << line << endl;
cout << endl;
// String Character
cout << "Enter a character to look for in your string: ";
cin >> lookfor;
cout << "The rest of your string after <" << lookfor << "> is <" << my_strchr(line, lookfor) << ">" << endl;
cout << endl;
// String String
cout << "Enter a word to look for in your string: ";
cin >> string;
cout << "The rest of your line after this is: " << "<" << my_strstr(line, string) << ">" << endl;
return 0;
}
Embedded for loop and a boolean that will tell you if the compare passed or failed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
char *my_strstr(char *str, char *oldline)
{
bool found = false;
while (!found)
{
if(*str == *oldline)
//for that compares all letters
if(!found)
str++;
}
return found ? str : -1; //-1 can be any invalid position that is easily recognizable
}
Also, you never check for the null terminator. If the character you're looking for isn't in the string, you'll go as far as the computer will let you until you find something.