example3_string_searching.cpp

 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
#include <cstring>
#include <iostream>

int main() {
    const char* haystack = "The quick brown fox jumps over the lazy dog";
    const char* needle = "fox";

    // Find first occurrence of a substring
    const char* result = std::strstr(haystack, needle);
    if (result) {
        std::cout << "Substring \"" << needle << "\" found at position: " 
                  << (result - haystack) << std::endl;
    } else {
        std::cout << "Substring not found" << std::endl;
    }

    // Find first occurrence of a character
    char ch = 'q';
    const char* ch_result = std::strchr(haystack, ch);
    if (ch_result) {
        std::cout << "Character '" << ch << "' found at position: " 
                  << (ch_result - haystack) << std::endl;
    } else {
        std::cout << "Character not found" << std::endl;
    }

    // Find last occurrence of a character
    ch = 'o';
    const char* last_ch = std::strrchr(haystack, ch);
    if (last_ch) {
        std::cout << "Last occurrence of '" << ch << "' found at position: " 
                  << (last_ch - haystack) << std::endl;
    } else {
        std::cout << "Character not found" << std::endl;
    }

    return 0;
}
Back to cstring