1

say i have a string:

a,b,c,d,e-f,g,h,

And i want to check if it contains the substring abcdefgh with skips of 1 character. I may change it later to a different skip count or even check for any match with different skips between the characters.

What would be that best way to approach this? is there anything out there in c that maybe i'm missing?

Tom
  • 9,275
  • 25
  • 89
  • 147

2 Answers2

0

You could do a regular express search for the string "a.b.c.d.e.f.g.h" (where dot matches any character). You could generalize that to use separator strings of length one or more chars with this regular expression: "a.+b.+c.+d.+e.+f.+g.+h" (change the + to a * to use separators of length zero or more chars). Here's some guidance on using REs in C: Regular expressions in C: examples?

Using REs may be a little easier but will also be more costly in terms of runtime performance. A faster solution would be to write a function that takes a search string, a separator, and a string to search and looks for the search string, while skipping the separator char. This is a good exercise in C programming -- even if you find an easier way, I think you'll get a lot out of writing this function yourself.

Community
  • 1
  • 1
Marc Cohen
  • 3,742
  • 2
  • 19
  • 19
0

A simple for loop will do just fine:

const char *d = "abcdefgh";
const char *s = "a,b,c,d,e-f,g,h,";
int len = strlen(s);

for (i=0; i<len; i+=2) {
    if (s[i] != d[i/2]) {
        /* not equal */
        break;
    }
}

Note: you should check the string has at least twice the length of the other one first.

iabdalkader
  • 17,009
  • 4
  • 47
  • 74