Advertisement
onix_hoque

CSE206 Week 5 - String Class

Apr 5th, 2018
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1.  
  2. #include <iostream>
  3. #include <cstdio>
  4.  
  5. using namespace std;
  6. class String
  7. {
  8.     char * pt;
  9.     int len;
  10. public:
  11.     String(int l)
  12.     {
  13.         len = l;
  14.         pt = new char[len];
  15.     }
  16.  
  17.     ~String()
  18.     {
  19.         delete [] pt;
  20.     }
  21.  
  22.     String (const String& st)
  23.     {
  24.         len = st.len;
  25.         pt = new char[len];
  26.         for (int i = 0; i<len; i++)
  27.             pt[i] = st.pt[i];
  28.     }
  29.  
  30.     char get(int index)
  31.     {
  32.         if (index >= len || index < 0)
  33.             return 0;
  34.         else
  35.             return pt[index];
  36.     }
  37.     int put(int index, char c)
  38.     {
  39.         if (index >= len || index < 0)
  40.             return -1;
  41.         else
  42.             pt[index] = c;
  43.     }
  44.     int getLength()
  45.     {
  46.         return len;
  47.     }
  48.     void display()
  49.     {
  50.         for (int i = 0; i<len; i++)
  51.             printf("%c", pt[i]);
  52.         printf("\n");
  53.     }
  54.     friend void compare(String s1, String s2);
  55. };
  56. void compare(String s1, String s2)
  57. {
  58.     if (s1.getLength() > s2.getLength())
  59.         cout << "The first string is greater"<<endl;
  60.     else if (s1.getLength() < s2.getLength())
  61.         cout << "The second string is greater"<<endl;
  62.     else
  63.         cout << "Both are equal"<<endl;
  64. }
  65. int main()
  66. {
  67.     String s1(4);
  68.     String s2(5);
  69.     String s3(5);
  70.     s1.put(0, 'A');
  71.     s1.put(1, 'B');
  72.     s1.put(2, 'C');
  73.     s1.put(3, 'D');
  74.     s1.display();     //ABCD
  75.  
  76.     s2.put(0, '1');
  77.     s2.put(1, '2');
  78.     s2.put(2, '3');
  79.     s2.put(3, '4');
  80.     s2.display();     //1234
  81.  
  82.     compare(s1, s2);
  83.     compare(s2, s1);
  84.     compare(s2, s3);
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement