← All problems · Pointers & Strings
Find All Occurrences of a Pattern in a String
Find every starting index where a nonempty pattern occurs in text, including overlapping matches. Store at most cap indices in out and return the total match count. Empty patterns return zero.
Implement size_t find_pattern(const char *text, const char *pattern, size_t *out, size_t cap).
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.
Slide the pattern across the text, comparing characters at each offset.
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <limits.h>
size_t find_pattern(const char *text, const char *pattern, size_t *out, size_t cap)
{
size_t n=strlen(text),m=strlen(pattern),k=0;
if(!m || m>n)return 0;
for(size_t i=0;i<=n-m;++i){
size_t j=0;while(j<m && text[i+j]==pattern[j])++j;
if(j==m){if(k<cap)out[k]=i;++k;}
}
return k;
}
#include <cstdio>
#include <cstdint>
#include <cstddef>
#include <cstring>
#include <climits>
std::size_t find_pattern(const char *text, const char *pattern, std::size_t *out, std::size_t cap)
{
std::size_t n=std::strlen(text),m=std::strlen(pattern),k=0;
if(!m || m>n)return 0;
for(std::size_t i=0;i<=n-m;++i){
std::size_t j=0;while(j<m && text[i+j]==pattern[j])++j;
if(j==m){if(k<cap)out[k]=i;++k;}
}
return k;
}
The naive search checks every possible start, so overlapping matches are found. Check m<=n before subtracting lengths. Worst-case O(n*m).
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)
{
size_t out[4];
CHECK(find_pattern("sensor-sensor","sensor",out,4)==2 && out[0]==0 && out[1]==7);
CHECK(find_pattern("aaaa","aa",out,4)==3 && out[0]==0 && out[1]==1 && out[2]==2);
CHECK(find_pattern("aaaa","aa",out,1)==3 && out[0]==0);
CHECK(find_pattern("abc","abcd",out,4)==0);
CHECK(find_pattern("abc","",out,4)==0);
CHECK(find_pattern("aaaa","aa",NULL,0)==3);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}