home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snipps97.zip / BASTRNGS.C < prev    next >
C/C++ Source or Header  |  1997-07-05  |  1KB  |  43 lines

  1. .I 0 1
  2. /* +++Date last modified: 05-Jul-1997 */
  3. .D 1 1
  4. .I 158 24
  5. /*
  6. **  BASIC INSTR$() work alike - returns position (1-based) of findstr in
  7. **  string, starting search at position start_pos (also 1-based).
  8. **
  9. **  Function suggested by Tika Carr
  10. */
  11.  
  12. unsigned int instr(const unsigned int start_pos,
  13.                    const char        *string,
  14.                    const char        *findstr)
  15. {
  16.       char *p;
  17.       unsigned int pos;
  18.  
  19.       if (start_pos > strlen(string))
  20.             return 0;
  21.       else  pos = start_pos - 1;    /* BASIC offsets are one-based, not
  22.                                        zero-based as in C               */
  23.  
  24.       if (NULL != (p = strstr(string + pos, findstr)))
  25.             return (int)(p - (char *)string) + 1; /* Position 0 = position 1 */
  26.       else  return 0;
  27. }
  28.  
  29. .I 167 3
  30.       char *a = "This is a test", *b = "is" ,
  31.            *c = "\nSearching for \"%s\" in \"%s\" starting at position %d\n";
  32.       unsigned int i, pos;
  33. .I 171 9
  34.  
  35.       for (i = 2; i < strlen(a); i+= 2)
  36.       {
  37.             printf(c, b, a, i);
  38.             if (0 != (pos = instr(i, a, b)))
  39.                   printf("Found at position %d\n", pos);
  40.             else  puts("Not found");
  41.       }
  42.  
  43.