Advertisement
Guest User

Cunstom String Class

a guest
Jun 20th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1. #include <iostream>
  2.  
  3.  
  4. enum { STRLEN_MAX = 255 };
  5.  
  6. class String {
  7. public:
  8.     char s[STRLEN_MAX];
  9.    
  10.     String() {
  11.         s[0] = 0;
  12.     }
  13.    
  14.     String(const char *x) {
  15.         s[0] = 0;
  16.         int i = 1;
  17.         while (*x && i < STRLEN_MAX) {
  18.             s[i] = *x;
  19.             ++x;
  20.             ++i;
  21.         }
  22.         s[0] = i - 1;
  23.     }
  24.    
  25.     char &operator [](int i) {
  26.         if (i > STRLEN_MAX) {
  27.             std::cerr << "Index out of range\n";
  28.             return s[0];
  29.         }
  30.         return s[i];
  31.     }
  32.    
  33.     char operator [](int i) const {
  34.         if (i > s[0]) {
  35.             std::cerr << "Index out of range\n";
  36.             return s[0];
  37.         }
  38.         return s[i];
  39.     }
  40.    
  41.     int get_len() const {
  42.         return s[0];
  43.     }
  44.    
  45.     String(const String &other) {
  46.         for (int i = 0; i <= other.get_len(); ++i) {
  47.             s[i] = other[i];
  48.         }
  49.     }
  50.    
  51.     String operator +(const String &other) {
  52.         String res(*this);
  53.         int i = 1;
  54.         while (res[0] + 1 < STRLEN_MAX && i <= other.get_len()) {
  55.             res[res[0] + 1] = other[i];
  56.             ++i;
  57.             ++res[0];
  58.         }
  59.         return res;
  60.     }
  61. };
  62.  
  63.  
  64. std::ostream& operator <<(std::ostream &out, const String &S) {
  65.     for (char i = 1; i <= S.get_len(); ++i) {
  66.         out << S[i];
  67.     }
  68.     return out;
  69. }
  70.  
  71. int main() {
  72.     String X("abcdef");
  73.     String Y("ababa");
  74.     String T = X;
  75.     std::cout << T << '\n';
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement