Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,753 questions

55,518 answers

573 users

How to search a string using bitwise operators C++

1 Answer

0 votes
#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

*/

 



answered Aug 5 by avibootz
...