How to check if second string is subsequence of first string in C++

1 Answer

0 votes
#include <iostream>

bool isSecondStringSubsequenceOfFirstString(const char* first, const char* second) {
    int i = 0, j = 0;
    
    while (first[i] != '\0') {
        if (second[j] == '\0') {
            return false;
        }
        
        if (first[i] == second[j]) {
            std::cout << "first[i] = " << first[i] << " second[j] = " << second[j];
            std::cout << " i = " << i << " j = " << j << "\n";
            i++;
            
        }
        
        j++;
    }
    
    return true;
}

int main() {
    const char* first = "c programming";
    const char* second = "c++ programming";
    
    std::cout << (isSecondStringSubsequenceOfFirstString(first, second) ? "yes" : "no");
}



/*
run:

first[i] = c second[j] = c i = 0 j = 0
first[i] =   second[j] =   i = 1 j = 3
first[i] = p second[j] = p i = 2 j = 4
first[i] = r second[j] = r i = 3 j = 5
first[i] = o second[j] = o i = 4 j = 6
first[i] = g second[j] = g i = 5 j = 7
first[i] = r second[j] = r i = 6 j = 8
first[i] = a second[j] = a i = 7 j = 9
first[i] = m second[j] = m i = 8 j = 10
first[i] = m second[j] = m i = 9 j = 11
first[i] = i second[j] = i i = 10 j = 12
first[i] = n second[j] = n i = 11 j = 13
first[i] = g second[j] = g i = 12 j = 14
yes

*/

 



answered Mar 24, 2024 by avibootz
edited Mar 24, 2024 by avibootz

Related questions

...