String.c 1.6 KB

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