← All problems · Pointers & Strings
Check Whether One String Is a Subsequence of Another
Return 1 if sub can be formed by deleting zero or more characters from text without changing the order of remaining characters. Empty sub always matches.
Implement int is_subsequence(const char *text, const char *sub).
Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Advance the subsequence pointer only on a matching character.
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <limits.h>
int is_subsequence(const char *text, const char *sub)
{
while(*text && *sub){if(*text==*sub)++sub;++text;}
return *sub=='\0';
}
#include <cstdio>
#include <cstdint>
#include <cstddef>
#include <cstring>
#include <climits>
int is_subsequence(const char *text, const char *sub)
{
while(*text && *sub){if(*text==*sub)++sub;++text;}
return *sub=='\0';
}
Stop once all subsequence characters have matched. Matching need not be contiguous.
solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
CHECK(is_subsequence("ABCD","AC")==1);
CHECK(is_subsequence("ABCD","CA")==0);
CHECK(is_subsequence("ABCD","")==1);
CHECK(is_subsequence("","A")==0);
CHECK(is_subsequence("abc","abcd")==0);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}