forked from i-am-lax/cpp-challenges
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubstring.cpp
More file actions
54 lines (48 loc) · 1.31 KB
/
Copy pathsubstring.cpp
File metadata and controls
54 lines (48 loc) · 1.31 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
#include <cstring>
#include <iostream>
using namespace std;
// Iterative version to check if s1 is a prefix of s2
// bool is_prefix(const char *s1, const char *s2) {
// while ((*s1 != '\0') && (*s2 != '\0')) {
// if (*s1 != *s2) {
// return false;
// }
// s1++;
// s2++;
// }
// return true;
// }
// Recursive version to check if s1 is a prefix of s2
bool is_prefix(const char *s1, const char *s2) {
if (*s1 == '\0') {
return true;
}
if (*s1 == *s2) {
return is_prefix(++s1, ++s2);
}
return false;
}
/* Recursive function to search for s1 as a substring in s2 and return position
* of first instance otherwise -1 if not found */
int substring_position(const char *s1, const char *s2) {
static int position = 0;
int output;
if (is_prefix(s1, s2)) {
// store position in variable output and clear position
output = position;
position = 0;
return output;
}
if (*s2 == '\0') {
position = 0;
return -1;
} else {
position++;
return substring_position(s1, ++s2);
}
}
// Alternative version to substring_position() which uses strstr()
int substring_position2(const char *s1, const char *s2) {
const char *p = strstr(s2, s1);
return (p) ? p - s2 : -1;
}