String.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include "String.h"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <strings.h>
  6. void stringInit(String* s)
  7. {
  8. s->length = 0;
  9. s->data = NULL;
  10. }
  11. void stringRemove(String* s)
  12. {
  13. s->length = 0;
  14. if(s->data != NULL)
  15. {
  16. free(s->data);
  17. s->data = NULL;
  18. }
  19. }
  20. int stringGetLength(String* s)
  21. {
  22. return s->length;
  23. }
  24. void stringRead(String* s)
  25. {
  26. int buffer = 16;
  27. int index = 0;
  28. char* chars = malloc(sizeof(char) * buffer);
  29. while(1)
  30. {
  31. int c = fgetc(stdin);
  32. if(c == EOF || c == '\n')
  33. {
  34. break;
  35. }
  36. if(index == buffer)
  37. {
  38. char* newBuffer = malloc(sizeof(char) * buffer * 2);
  39. memcpy(newBuffer, chars, buffer);
  40. free(chars);
  41. chars = newBuffer;
  42. buffer *= 2;
  43. }
  44. chars[index] = c;
  45. index++;
  46. }
  47. s->length = index;
  48. s->data = malloc(sizeof(char) * (index + 1));
  49. memcpy(s->data, chars, index);
  50. free(chars);
  51. s->data[index] = '\0';
  52. }
  53. int stringCompare(String* s, const char* chars)
  54. {
  55. return strcmp(s->data, chars) == 0;
  56. }
  57. int stringCompareNoCase(String* s, const char* chars)
  58. {
  59. return strcasecmp(s->data, chars) == 0;
  60. }