TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
brute_force_string_searching.cpp
Go to the documentation of this file.
1
5#include <iostream>
6#ifdef _MSC_VER
7#include <string> // use this for MS Visual C++
8#else
9#include <cstring>
10#endif
11#include <vector>
12
13namespace string_search {
21int brute_force(const std::string &text, const std::string &pattern) {
22 size_t pat_l = pattern.length();
23 size_t txt_l = text.length();
24 int index = -1;
25 if (pat_l <= txt_l) {
26 for (size_t i = 0; i < txt_l - pat_l + 1; i++) {
27 std::string s = text.substr(i, pat_l);
28 if (s == pattern) {
29 index = i;
30 break;
31 }
32 }
33 }
34 return index;
35}
36} // namespace string_search
37
39
41const std::vector<std::vector<std::string>> test_set = {
42 // {text, pattern, expected output}
43 {"a", "aa", "-1"}, {"a", "a", "0"}, {"ba", "b", "0"},
44 {"bba", "bb", "0"}, {"bbca", "c", "2"}, {"ab", "b", "1"}};
45
47int main() {
48 for (const auto &i : test_set) {
49 int output = brute_force(i[0], i[1]);
50
51 if (std::to_string(output) == i[2]) {
52 std::cout << "success\n";
53 } else {
54 std::cout << "failure\n";
55 }
56 }
57 return 0;
58}
const std::vector< std::vector< std::string > > test_set
String search algorithms.
int brute_force(const std::string &text, const std::string &pattern)