thespeedracer38

String Implementation

Feb 4th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.63 KB | None | 0 0
  1. /* Implementing String class
  2. */
  3.  
  4. #include <iostream>
  5. #include <cstdlib>
  6. #include <cstring>
  7. #include <cstdio>
  8.  
  9. using namespace std;
  10.  
  11. class String{
  12.     char *str;
  13.     int size;
  14.     public:
  15.         String(const char* = "");
  16.         ~String();
  17.         int length();
  18.         bool operator >(String&);
  19.         bool operator <(String&);
  20.         bool operator ==(String&);
  21.         friend istream& operator >>(istream&, String&);
  22.         friend ostream& operator <<(ostream&, String&);
  23. };
  24.  
  25. inline String::String(const char *str){
  26.     String::str = new char[strlen(str) + 1];
  27.     strcpy(String::str, str);
  28.     size = strlen(str);
  29. }
  30.  
  31. inline String::~String(){
  32.     delete[] str;
  33.     str = NULL;
  34. }
  35.  
  36. inline int String::length(){
  37.     return size;
  38. }
  39.  
  40. inline bool String::operator >(String &obj){
  41.     return strcmp(str, obj.str) > 0;
  42. }
  43.  
  44. inline bool String::operator <(String &obj){
  45.     return strcmp(str, obj.str) < 0;
  46. }
  47.  
  48. inline bool String::operator ==(String &obj){
  49.     return strcmp(str, obj.str) == 0;
  50. }
  51.  
  52. istream& operator >>(istream &in, String &obj){
  53.     /* Try to do this in the constructor */
  54.     char temp[1024];
  55.     gets(temp);
  56.     delete[] obj.str;
  57.     obj.str = new char[strlen(temp) + 1];
  58.     strcpy(obj.str, temp);
  59.     return in;
  60. }
  61.  
  62. ostream& operator <<(ostream &out, String &obj){
  63.     out << obj.str;
  64.     return out;
  65. }
  66.  
  67. int main() {
  68.     system("cls");
  69.     cout << "Enter the first string: ";
  70.     String str1;
  71.     cin >> str1;
  72.     cout << "Enter the second string: ";
  73.     String str2;
  74.     cin >> str2;
  75.     if(str1 > str2){
  76.         cout << str1 << " is greater than " << str2;
  77.     }
  78.     else if(str1 < str2){
  79.         cout << str1 << " is lesser than " << str2;
  80.     }
  81.     else {
  82.         cout << str1 << " is equal to " << str2;
  83.     }
  84.     cin.get();
  85.     return 0;
  86. }
Add Comment
Please, Sign In to add comment