Advertisement
Guest User

Untitled

a guest
Oct 4th, 2015
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. struct String {
  4. String (String const& other) {
  5. size = other.size;
  6. if (size > 0) {
  7. str = new char[size + 1];
  8. str[size] = '';
  9.  
  10. const char * i = other.str;
  11. while (i != other.str + other.size) {
  12. str[i - other.str] = *i;
  13. i++;
  14. };
  15. } else {
  16. str = 0;
  17. }
  18. }
  19.  
  20. String(const char *str = "") {
  21. size = 0;
  22. this->str = 0;
  23. size = lengthOfStr(str);
  24. this->str = (size > 0) ? cpStr(str, size) : 0;
  25. }
  26.  
  27. String(size_t n, char c) {
  28. size = n;
  29. str = new char[size + 1];
  30. str[size] = '';
  31. char * i = str;
  32. while (i - str < size) {
  33. *i = c;
  34. i++;
  35. };
  36. }
  37.  
  38. ~String() {
  39. if (str != 0)
  40. delete [] str;
  41. str = 0;
  42. size = 0;
  43. }
  44.  
  45. void append(String &other) {
  46. size_t newSz = size + other.size;
  47. char *newStr = new char[newSz + 1];
  48. newStr[newSz] = '';
  49.  
  50. const char * i = str;
  51. while (i != str + size) {
  52. newStr[i - str] = *i;
  53. i++;
  54. };
  55.  
  56. i = other.str;
  57. while (i != other.str + other.size) {
  58. newStr[size + i - other.str] = *i;
  59. i++;
  60. };
  61.  
  62. delete [] str;
  63. size = newSz;
  64. str = newStr;
  65. }
  66.  
  67. size_t lengthOfStr(const char * const str) {
  68. const char * i = str;
  69. while (*i != '') {
  70. i++;
  71. };
  72. return i - str;
  73. }
  74.  
  75. char* cpStr(const char * const str, size_t strSz) {
  76. char *newStr = new char[strSz + 1];
  77. newStr[strSz] = '';
  78.  
  79. const char * i = str;
  80. while (i != str + strSz) {
  81. newStr[i - str] = *i;
  82. i++;
  83. };
  84.  
  85. return newStr;
  86. }
  87.  
  88. size_t size;
  89. char *str;
  90. };
  91.  
  92. int test2() {
  93. String ten_spaces;
  94. ten_spaces = String(10, ' ');
  95. std::cout << ten_spaces.str << "n";
  96. return 0;
  97. }
  98.  
  99. int main(int argc, const char * argv[]) {
  100. test2();
  101. return 0;
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement