// chset.cpp #include "chset.h" #include "pmglobs.h" #include #include // constructor: chset::chset(const char* s) { //cout << "in chset constructor\n"; if (s == NULL) { set = NULL; } else { int i = 0; while (s[i] != '\0') i++; // counts number of chars in s. int size = i + 1; // for space allocation char* tempStr = new char[size]; // allocates space to hold s. for (int j = 0; j < size; j++) tempStr[j] = '\0'; // initialize int k = 0; for (j = 0; j < size; j++) { if (strchr(tempStr, s[j]) == NULL) { tempStr[k] = s[j]; k++; } } // end of for loop. tempStr[k] = '\0'; // end string with NULL character. char* tempStr2 = new char[k+1]; // alloc space to hold set members for (i = 0; i < k + 1; i++) tempStr2[i] = tempStr[i]; // copy. tempStr2[k+1] = '\0'; delete tempStr; set = tempStr2; // pointer assignment. } // end of if-else. } // end of constructor. chset::~chset() { // destructor delete set; set = NULL; } bool chset::in(char ch) const { // test if char ch in set set. return bool(strchr(set, ch) != NULL); } void chset::incl(char ch) { // add char ch into set set. if ( !in(ch) ) { int k = strlen(set); char* tempStr = new char[k+2]; // 1 space for ch and 1 for NULL strcpy(tempStr, set); // copy string set to string tempStr. tempStr[k] = ch; // assign ch to kth position tempStr[k+1] = '\0'; // terminate string with NULL. delete set; set = tempStr; // reset set to new set. } // end of if. } // end of method incl. void chset::operator<(char ch) { // not sure what do this method do. } chset operator+(const chset& c1, const chset& c2) { // set union. int k = strlen(c1.set); int j = k; for (int i = 0; i < strlen(c2.set); i++) { if ( !c1.in(c2.set[i]) ) k++; // make space for set union. } // end of for loop. char* tempStr = new char[k+1]; strcpy(tempStr, c1.set); for (i = 0; i < strlen(c2.set); i++) { if ( !c1.in(c2.set[i]) ) { tempStr[j] = c2.set[i]; // add extra elements of c2 to tempStr. j++; } // end of if } // enf of for loop. tempStr[j] = '\0'; // teinate string with '\0' char. chset aChset(tempStr); return aChset; } chset& chset::operator=(const chset& c) { set = strdup(c.set); return *this; } ostream& operator<<(ostream& co, const chset& c) { co << "{" << c.set << "}"; return co; }