String.cpp 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include <cstring>
  2. #include <cstdio>
  3. #include "utils/String.h"
  4. String::String() : length(0) {
  5. data[0] = '\0';
  6. }
  7. String::String(const char* str) : length(0) {
  8. for(; length < MAX_LENGTH - 1 && str[length] != '\0'; length++) {
  9. data[length] = str[length];
  10. }
  11. data[length] = '\0';
  12. }
  13. bool String::operator==(const String& other) const {
  14. return length == other.length && strcmp(data, other.data) == 0;
  15. }
  16. bool String::operator!=(const String& other) const {
  17. return !(*this == other);
  18. }
  19. String::operator const char*() const {
  20. return data;
  21. }
  22. char String::operator[](uint index) const {
  23. return data[index];
  24. }
  25. uint String::getLength() const {
  26. return length;
  27. }
  28. String& String::append(char c) {
  29. if(length < MAX_LENGTH - 1) {
  30. data[length++] = c;
  31. data[length] = '\0';
  32. }
  33. return *this;
  34. }
  35. String& String::append(const char* str) {
  36. for(uint i = 0; length < MAX_LENGTH - 1 && str[i] != '\0'; length++, i++) {
  37. data[length] = str[i];
  38. }
  39. data[length] = '\0';
  40. return *this;
  41. }
  42. String& String::append(int i) {
  43. uint left = MAX_LENGTH - length;
  44. uint written = snprintf(data + length, left, "%d", i);
  45. if(written < left) {
  46. length += written;
  47. } else {
  48. length = MAX_LENGTH;
  49. }
  50. return *this;
  51. }
  52. String& String::append(float f) {
  53. uint left = MAX_LENGTH - length;
  54. uint written = snprintf(data + length, left, "%.2f", f);
  55. if(written < left) {
  56. length += written;
  57. } else {
  58. length = MAX_LENGTH;
  59. }
  60. return *this;
  61. }