fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <errno.h>
  4. #include <string.h>
  5.  
  6. #define MAX_LENGTH 100
  7.  
  8. char* StrStr(const char *str, const char *target);
  9.  
  10. int main(void) {
  11. char *result, *pointer;
  12. char inputstring[MAX_LENGTH]; // here we define a new char array (string) which will be used for the input.
  13.  
  14. /**
  15.   * fgets is used to read a string until a newline (i.e press return key)
  16.   * from stdin and into inputstring with a limit of MAX_LENGTH characters.
  17.   * It can be thought of as a way to get input from the user. Instead you
  18.   * could set inputstring to a predefined array of characters (in the code).
  19.   */
  20. fgets(inputstring, MAX_LENGTH, stdin);
  21. pointer = inputstring; // set pointer to the address of inputstring
  22. while((result = StrStr(pointer, "a!c")) != NULL) { // while "a!c" can be found in the remainder of inputstring
  23. int position = result - inputstring; // get the position (i.e index of the target)
  24. pointer += position+1; // to avoid finding the same target indefinitely add position+1 to the pointer
  25. printf("%d\n", position); // print the index to stdout (i.e the console)
  26. }
  27. }
  28.  
  29. char* StrStr(const char *str, const char *target) {
  30. if (!*target) return NULL;
  31. char *p1 = (char*)str;
  32. while (*p1) { // is the pointer pointing at a NUL terminator? If isn't do what is inside the while loop
  33. char *p1Begin = p1, *p2 = (char*)target;
  34. /**
  35.   * is the pointers p1 and p2 not pointing to a NUL terminator?
  36.   * is the pointers also pointing at the equivalent data?
  37.   * or is p2 pointing at an exclamation mark?
  38.   * If these conditions are true then point to the next character in str and target.
  39.   */
  40. while ((*p1 && *p2 && *p1 == *p2) || *p2 == '!') {
  41. p1++;
  42. p2++;
  43. }
  44. if (!*p2)
  45. return p1Begin;
  46. p1 = p1Begin + 1;
  47. }
  48. return NULL;
  49. }
  50.  
Success #stdin #stdout 0s 2160KB
stdin
abcdefghijklmopqrstuvwxyzaxc
stdout
0
25