定义一个字符串类DelSameStr,从左到右对字符串中每个字符删除其后所有相同的字符,只留下第一次出现的那一个

定义一个字符串类DelSameStr,从左到右对字符串中每个字符删除其后所有相同的字符,只留下第一次出现的那一个。例如,若字符串为”cocoon”,删除重复出现的字符后,其结果是字符串”con”。具体要求如下:

(1)私有数据成员。

char *s1:指向原字符串。

char *s2:指向结果字符串。

(2) 公有成员函数。

DelSameStr(char *s):构造函数,动态分配s1和s2指向的空间,并用s初始化s1。

void delsame():删除重复出现的字符。

void show():输出原字符串和结果字符串。

~DelSameStr():析构函数,释放动态分配的存储空间。

(3) 在主函数中定义一个DelSameStr类的对象test,用字符串”cocoon”初始化test,通过test调用成员函数完成删除工作,输出删除前后的两个字符串。

扫描二维码关注公众号,回复: 2438973 查看本文章
#include "string"
#include <iostream> 

using namespace std;

class DelSameStr
{
private:
	char *s1;
	char *s2;
public:
	DelSameStr(char *s);
	void delsame();
	void show();
	~DelSameStr();
};
DelSameStr::DelSameStr(char *s)
{
	s1 = new char[sizeof(s)];
	s2 = new char[sizeof(s)];
	s1 = s;
}
DelSameStr::~DelSameStr()
{
	delete[] s1;
	delete[] s2;
}
void DelSameStr::delsame()
{
	int i = 0;
	int j = 0;

	s2[0] = '\0';
	while (s1[i] != '\0')
	{
		j = 0;
		while (s2[j] != '\0')
		{
			if (s1[i] != s2[j])
			{
				j++;
			}
			else
			{
				break;
			}
		}
		if (s2[j] == '\0')
		{
			s2[j++] = s1[i];
			s2[j] = '\0';
		}
		i++;
	}
}

void DelSameStr::show()
{
	cout << "原字符串为:" << s1 << endl;
	cout << "结果字符串为:" << s2 << endl;
}
int main()
{
	DelSameStr text("cocoon");
	text.delsame();
	text.show();
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/cxycj123/article/details/79763731
今日推荐