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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,907 questions

51,839 answers

573 users

How to create a case-insensitive function for substring search in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <algorithm>

// Function to convert a string to lowercase
std::string toLower(const std::string& str) {
    std::string lowerStr = str;
    std::transform(lowerStr.begin(), lowerStr.end(), lowerStr.begin(),
                   [](unsigned char c) { return std::tolower(c); });
                   
    return lowerStr;
}

// Case-insensitive substring search function
const char* strstrcaseinsensitive(const char* haystack, const char* needle) {
    std::string haystackStr = haystack;
    std::string needleStr = needle;
    
    std::string lowerHaystack = toLower(haystackStr);
    std::string lowerNeedle = toLower(needleStr);
    
    size_t pos = lowerHaystack.find(lowerNeedle);
    if (pos != std::string::npos) {
        return haystack + pos;
    } 
    
    return nullptr;
}

int main() {
    const char* haystack = "C++ is a general-purpose programming language";
    const char* needle = "PROGRAMMING";
    
    const char* result = strstrcaseinsensitive(haystack, needle);
    if (result) {
        std::cout << "Found: " << result << std::endl;
    } else {
        std::cout << "Not Found" << std::endl;
    }
}


/*
run:

Found: programming language

*/

 



answered Feb 5, 2025 by avibootz
...