compare_string_array.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  4. */
  5. #include "libbb.h"
  6. /* returns the array index of the string */
  7. /* (index of first match is returned, or -1) */
  8. int FAST_FUNC index_in_str_array(const char *const string_array[], const char *key)
  9. {
  10. int i;
  11. for (i = 0; string_array[i] != 0; i++) {
  12. if (strcmp(string_array[i], key) == 0) {
  13. return i;
  14. }
  15. }
  16. return -1;
  17. }
  18. int FAST_FUNC index_in_strings(const char *strings, const char *key)
  19. {
  20. int idx = 0;
  21. while (*strings) {
  22. if (strcmp(strings, key) == 0) {
  23. return idx;
  24. }
  25. strings += strlen(strings) + 1; /* skip NUL */
  26. idx++;
  27. }
  28. return -1;
  29. }
  30. /* returns the array index of the string, even if it matches only a beginning */
  31. /* (index of first match is returned, or -1) */
  32. #ifdef UNUSED
  33. int FAST_FUNC index_in_substr_array(const char *const string_array[], const char *key)
  34. {
  35. int i;
  36. int len = strlen(key);
  37. if (len) {
  38. for (i = 0; string_array[i] != 0; i++) {
  39. if (strncmp(string_array[i], key, len) == 0) {
  40. return i;
  41. }
  42. }
  43. }
  44. return -1;
  45. }
  46. #endif
  47. int FAST_FUNC index_in_substrings(const char *strings, const char *key)
  48. {
  49. int len = strlen(key);
  50. if (len) {
  51. int idx = 0;
  52. while (*strings) {
  53. if (strncmp(strings, key, len) == 0) {
  54. return idx;
  55. }
  56. strings += strlen(strings) + 1; /* skip NUL */
  57. idx++;
  58. }
  59. }
  60. return -1;
  61. }
  62. const char* FAST_FUNC nth_string(const char *strings, int n)
  63. {
  64. while (n) {
  65. n--;
  66. strings += strlen(strings) + 1;
  67. }
  68. return strings;
  69. }