Simple Data Class using C++
Posted by Samath
Last Updated: January 07, 2021
  1247

Design a class Data using the description of the data members and member functions given below:

Class name :                   Data

Data members
str :                                  string variable of protected type to store a sentence.
len :                                 To Store the length of str

Member functions
Data() :                            constructor to assign blank to str.
void acceptstr() :              to read a sentence into str
void print() :                      to print value of str with suitable heading.
void removeDuplicate() :  to replace the duplicate characters in sequence by its single occurrence in the string str. For example “Heee iiiiss ggoiinggg hooommmeee”. The output should be “He is going home”. Note that the sequence of spaces should also be replaced by single space. Print the modified sentence.

Code:

#include <iostream>
#include <string>
#include <stdio.h>
#include <cstdlib>
#include <stdlib.h>
 
using namespace std;
 
class Data
{
	private:
		int len;
		string str;
 
	public:
		Data();
		void acceptstr(string s);
		void print();
		void removeDuplicate();
};
 
Data::Data()
{
	str = "";
}
 
void Data::removeDuplicate()
{
 
	char* strdup = new char[str.length() +1];
	 int tail = 1;
    int i, j;
 
	strdup[str.size()]=0;
	memcpy(strdup,str.c_str(),str.size());
 
 
    if(strdup == NULL)
        return;
 
    char *tmp = strdup;
 
    while(*tmp){
        tmp ++;
    }
 
    int len = tmp - strdup;
    if(len < 2)
        return;
 
 
    for(i = 1; i < len; i++)
	{
        for(j = 0; j < tail; j++)
		{
			if(strdup[i] != strdup[i - 1])
			{
				continue;
			}
            if(strdup[i] == strdup[j])
			{
                break;
            }
        }
 
        if(j == tail)
		{
            strdup[tail] = strdup[i];
            tail ++;
        }
    }
 
    strdup[tail] = '\0';
 
   string mystring = string(strdup);
 
   str = mystring;
 
    cout<<"Modified Sentense: "<<str<<endl;
}
 
void Data::print()
{
	cout<<"String Value: "<<str<<endl;
}
 
void Data::acceptstr(string s)
{
	str = s;
}
 
int main()
{
	string newstr;
	Data info;
 
	cout<<"Please enter new string: ";
	getline(cin,newstr);
	info.acceptstr(newstr);
 
	info.removeDuplicate();
	system("pause");
	return 0;
}