-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplement_strStr.cpp
More file actions
55 lines (45 loc) · 1.38 KB
/
Copy pathImplement_strStr.cpp
File metadata and controls
55 lines (45 loc) · 1.38 KB
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
/*
Problem:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button to reset your code definition
*/
#include<iostream>
#include<cstring>
using namespace std;
int strStr(char *haystack, char *needle)
{
if (haystack == NULL)
{
if (needle == NULL) return 0;
else cout << "hi" << endl; return -1;
}
if (needle == NULL) return 0;
int len_haystack = strlen(haystack);
cout << len_haystack << endl;
int len_needle = strlen(needle);
cout << len_needle << endl;
for (int i = 0; i <= len_haystack - len_needle; i++)
{
for (int j = 0; j <= len_needle; j++)
{
char* a = haystack + i + j;
cout << "*a:" << *a << endl;
char* b = needle + j;
cout << "*b:" << *b << endl;
if (*b == '\0') return i;
if (*a != *b) break;
}
}
return -1;
}
int main()
{
char a[] = {'a','b','c','d','\0'};
char b[] = {'b','c','\0'};
int test;
test = strStr(a,b);
cout << test << endl;
return 0;
}