Repository navigation
Expand file tree
/
Copy pathTask8.cpp
More file actions
50 lines (43 loc) · 1.77 KB
/
Copy pathTask8.cpp
File metadata and controls
50 lines (43 loc) · 1.77 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
#include <iostream>
#include <string>
using namespace std;
int findSubstring(string sub, string mainString) {
if (sub.empty() || mainString.empty()) { // if the substring or main string is empty, we return -1
cout << "The substring or main string is missing ";
return -1;
}
int start = -1; // will hold the starting index of the match if found
int matchIndex = 0; // tracks progress through the substring
for (int i = 0; i < mainString.length(); i++) {
if (mainString[i] == sub[matchIndex]) {// if current characters match, move to next character of substring
if (matchIndex == 0) { // record potential starting index of the match
start = i;
}
matchIndex++;
if (matchIndex == sub.length()) {// if full substring matched, return the starting index
return start;
}
} else { // mismatch: reset the substring index
if (matchIndex > 0) {
i = i - matchIndex;
}
matchIndex = 0;
start = -1;
}
}
return -1; // substring not found
}
int main() {
string substring = "dib";
string t1 = "dibilical"; // test case 1
string t2 = "icaldib"; // test case 2
string t3 = "testString"; // test case 3
string t4 = "dildil"; // substring partially matches
cout << "Test case 1: " << findSubstring(substring, t1) << endl;
cout << "Test case 2: " << findSubstring(substring, t2) << endl;
cout << "Test case 3: " << findSubstring(substring, t3) << endl;
cout << "Test case 4: " << findSubstring(substring, t4) << endl;
cout << "Test case 5: " << findSubstring("", t4) << endl;
cout << "Test case 6: " << findSubstring(substring, "") << endl;
return 0;
}