strverscmp.c 708 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #define _GNU_SOURCE
  2. #include <ctype.h>
  3. #include <string.h>
  4. #include <sys/types.h>
  5. int strverscmp(const char *l, const char *r)
  6. {
  7. int haszero=1;
  8. while (*l==*r) {
  9. if (!*l) return 0;
  10. if (*l=='0') {
  11. if (haszero==1) {
  12. haszero=0;
  13. }
  14. } else if (isdigit(*l)) {
  15. if (haszero==1) {
  16. haszero=2;
  17. }
  18. } else {
  19. haszero=1;
  20. }
  21. l++; r++;
  22. }
  23. if (haszero==1 && (*l=='0' || *r=='0')) {
  24. haszero=0;
  25. }
  26. if ((isdigit(*l) && isdigit(*r) ) && haszero) {
  27. size_t lenl=0, lenr=0;
  28. while (isdigit(l[lenl]) ) lenl++;
  29. while (isdigit(r[lenr]) ) lenr++;
  30. if (lenl==lenr) {
  31. return (*l - *r);
  32. } else if (lenl>lenr) {
  33. return 1;
  34. } else {
  35. return -1;
  36. }
  37. } else {
  38. return (*l - *r);
  39. }
  40. }