Advertisement
bugaevc

mysubstr task

Sep 14th, 2015
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.04 KB | None | 0 0
  1. #include <string.h>
  2.  
  3. #define STAR_CHR '*'
  4. int
  5. mysubstr(char *needle, char *haystack)
  6. {
  7.     char *star = strchr(needle, STAR_CHR);
  8.     if (star != NULL) {
  9.         // separate two parts of the string
  10.         *star = 0;
  11.         // now needle is he first part
  12.         // and star + 1 is the second part
  13.     }
  14.     char *res = strstr(haystack, needle);
  15.     // NOTE: strstr uses reverse args order
  16.     if (star == NULL) {
  17.         // if there was no star, we're done
  18.         return res == NULL ? -1 : res - haystack;
  19.     }
  20.     if (res == NULL) {
  21.         *star = STAR_CHR;
  22.         return -1;
  23.     }
  24.     // search for the second part of the needle
  25.     // in the remaining part of the haystack
  26.     char *second_part = strstr(res + strlen(needle), star + 1);
  27.     *star = STAR_CHR;
  28.     return second_part == NULL ? -1 : res - haystack;
  29. }
  30.  
  31. #ifdef DEBUG
  32. #include <stdio.h>
  33. int main(void) {
  34.     char needle[80];
  35.     char haystack[80];
  36.     scanf("%s%s", needle, haystack);
  37.     printf("%d\n", mysubstr(needle, haystack));
  38.     return 0;
  39. }
  40. #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement