3
0

strrstr.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Utility routines.
  4. *
  5. * Copyright (C) 2008 Bernhard Reutner-Fischer
  6. *
  7. * Licensed under GPLv2 or later, see file License in this tarball for details.
  8. */
  9. #ifdef __DO_STRRSTR_TEST
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <stdio.h>
  13. #else
  14. #include "libbb.h"
  15. #endif
  16. /*
  17. * The strrstr() function finds the last occurrence of the substring needle
  18. * in the string haystack. The terminating nul characters are not compared.
  19. */
  20. char* FAST_FUNC strrstr(const char *haystack, const char *needle)
  21. {
  22. char *r = NULL;
  23. if (!needle[0])
  24. return (char*)haystack + strlen(haystack);
  25. while (1) {
  26. char *p = strstr(haystack, needle);
  27. if (!p)
  28. return r;
  29. r = p;
  30. haystack = p + 1;
  31. }
  32. }
  33. #ifdef __DO_STRRSTR_TEST
  34. int main(int argc, char **argv)
  35. {
  36. static const struct {
  37. const char *h, *n;
  38. int pos;
  39. } test_array[] = {
  40. /* 0123456789 */
  41. { "baaabaaab", "aaa", 5 },
  42. { "baaabaaaab", "aaa", 6 },
  43. { "baaabaab", "aaa", 1 },
  44. { "aaa", "aaa", 0 },
  45. { "aaa", "a", 2 },
  46. { "aaa", "bbb", -1 },
  47. { "a", "aaa", -1 },
  48. { "aaa", "", 3 },
  49. { "", "aaa", -1 },
  50. { "", "", 0 },
  51. };
  52. int i;
  53. i = 0;
  54. while (i < sizeof(test_array) / sizeof(test_array[0])) {
  55. const char *r = strrstr(test_array[i].h, test_array[i].n);
  56. printf("'%s' vs. '%s': '%s' - ", test_array[i].h, test_array[i].n, r);
  57. if (r == NULL)
  58. r = test_array[i].h - 1;
  59. printf("%s\n", r == test_array[i].h + test_array[i].pos ? "PASSED" : "FAILED");
  60. i++;
  61. }
  62. return 0;
  63. }
  64. #endif