String.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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[](int index) const {
  23. return data[index];
  24. }
  25. int String::getLength() const {
  26. return length;
  27. }
  28. String& String::clear() {
  29. length = 0;
  30. data[0] = '\0';
  31. return *this;
  32. }
  33. String& String::append(char c) {
  34. if(length < MAX_LENGTH - 1) {
  35. data[length++] = c;
  36. data[length] = '\0';
  37. }
  38. return *this;
  39. }
  40. String& String::append(const char* str) {
  41. for(int i = 0; length < MAX_LENGTH - 1 && str[i] != '\0'; length++, i++) {
  42. data[length] = str[i];
  43. }
  44. data[length] = '\0';
  45. return *this;
  46. }
  47. String& String::append(int i) {
  48. return append("%d", i);
  49. }
  50. String& String::append(float f) {
  51. return append("%.2f", f);
  52. }
  53. String& String::append(bool b) {
  54. return append(b ? "true" : "false");
  55. }