#include <iostream>
#include <string>
/*
This function performs substring search using bitwise operations.
The core idea:
- Two characters are equal if (a ^ b) == 0
- XOR is a fast bitwise operator, so we use it to compare characters.
- We slide over the text and compare each character of the pattern.
*/
bool containsUsingBitwise(const std::string& text, const std::string& pattern) {
// If the pattern is longer than the text, it cannot be found
if (pattern.size() > text.size()) return false;
// Loop over every possible starting position in the text
for (size_t i = 0; i <= text.size() - pattern.size(); ++i) {
bool match = true; // assume match until proven otherwise
// Compare each character using XOR
for (size_t j = 0; j < pattern.size(); ++j) {
// If XOR is non‑zero, characters differ
if ((text[i + j] ^ pattern[j]) != 0) {
match = false;
break; // no need to continue checking this position
}
}
// If all characters matched, return true
if (match) return true;
}
// No match found
return false;
}
int main() {
std::string text = "Compile, run, and edit code online";
std::string pattern = "code";
// Perform the search
bool found = containsUsingBitwise(text, pattern);
// Print result
std::cout << "Text: " << text << "\n";
std::cout << "Pattern: " << pattern << "\n";
std::cout << "Found: " << (found ? "yes" : "no") << "\n";
}
/*
run:
Text: Compile, run, and edit code online
Pattern: code
Found: yes
*/