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

1 Answer

0 votes
#include <stdio.h>
#include <stdbool.h>
 
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]) {
            printf("first[i] = %c  second[j] = %c", first[i], second[j]);
            printf(" i = %d j = %d\n", i, j);
            i++;
             
        }
         
        j++;
    }
     
    return true;
}
 
int main() {
    const char* first = "c programming";
    const char* second = "c++ programming";
     
    printf("%s\n", isSecondStringSubsequenceOfFirstString(first, second) ? "yes" : "no");
     
    return 0;
}
 
 
 
/*
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

...