Rewriting Strstr

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
  /*
*/

#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.
Perfect thank you. I didn't even think about how it could check for the whole line instead of just the first character. I can make it go from here.
Topic archived. No new replies allowed.