String.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #include <cstring>
  2. #include <cstdio>
  3. #include "common/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(uint i) {
  43. return append("%u", i);
  44. }
  45. String& String::append(int i) {
  46. return append("%d", i);
  47. }
  48. String& String::append(float f) {
  49. return append("%.2f", f);
  50. }
  51. String& String::append(bool b) {
  52. return append(b ? "true" : "false");
  53. }
  54. String& String::clear() {
  55. data[0] = '\0';
  56. length = 0;
  57. return *this;
  58. }