String.c 1.1 KB

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