-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstartingPos.cpp
More file actions
60 lines (49 loc) · 1.42 KB
/
startingPos.cpp
File metadata and controls
60 lines (49 loc) · 1.42 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
56
57
58
59
60
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
vector<int> findStartingPositions(const string& pattern, const string& text) {
size_t textLen = text.length();
size_t patternLen = pattern.length();
vector<int> positions;
for (size_t i = 0; i <= textLen - patternLen; i++) {
if (text.substr(i, patternLen) == pattern) {
positions.push_back(i);
}
}
return positions;
}
int main() {
// Input the pattern manually
string pattern;
cout << "Enter the pattern: ";
getline(cin, pattern);
// Read the text from a file
string filename;
cout << "Enter the filename containing the text: ";
getline(cin, filename);
ifstream file(filename);
if (!file) {
cerr << "Error opening file." << endl;
return 1;
}
// Read the entire file content as text
string text;
string line;
while (getline(file, line)) {
text += line;
}
file.close();
vector<int> positions = findStartingPositions(pattern, text);
if (positions.empty()) {
cout << "Pattern not found in the text." << endl;
} else {
cout << "The starting positions of the pattern are: ";
for (const int& position : positions) {
cout << position << " ";
}
cout << endl;
}
return 0;
}