建立一個存儲和處理字符串的類DelCharStr。
(1)私有數據成員
char *s:字符串的首地址。
int len:該字符串的長度值。
(2)公有成員函數
構造函數:動態申請存儲字符串所需內存空間,並且即能用指定的字符串也能用默認的值0爲所聲明的對象進行初始化。
析構函數:釋放字符串所用的內存空間。
void setstr(char *sn):重新設置str的值。
viud showstr():顯示字符串。
int getstrlen():返回字符串長度值。
void delchar(char ch):在字符串中查找並刪除指定的字符。
(3)按以下要求編寫程序測試該類。
定義DelCharStr對象s1,初始值爲”student”。
輸出s1中的字符串和長度值。
從s1字符串中刪除字符’t’,輸出s1中的字符串和長度值。
將”teacher”重新賦值給s1,輸出s1中的字符串和長度值。
// class3-4.cpp : 定義控制檯應用程序的入口點。
//構造函數:動態申請存儲字符串所需內存空間,並且即能用指定的字符串也能用默認的值0爲所聲明的對象進行初始化。
#include "stdafx.h"
#include <iostream>
#include <cstring>
using namespace std;
class DelCharStr
{
private:
char *s;
int len;
public:
DelCharStr(const char *str=0):s(NULL),len(0)//析構函數:釋放字符串所用的內存空間。
{
if(str)
{
len = strlen(str);
s = new char [len+1];
strcpy(s, str);
}
}
~DelCharStr()
{
if(s) delete[]s;
}
void setstr(char *sn)//重新設置str的值
{
if(s){delete []s; len = 0;s=NULL;}
if(sn)
{
len = strlen(sn);
s = new char [len+1];
strcpy(s, sn);
}
}
void showstr()//顯示字符串
{
cout << s <<endl;
}
int getstrlen()//返回字符串長度值。
{
return len;
}
void delchar(char ch)
{
int i,j;
for(i = j = 0; i < len; i ++)
{
if(s[i] != ch)
s[j++] = s[i];
}
len = j;
s[j] = '\0';
}
};
int main()
{
DelCharStr s1("student");
char ns[]="teacher";
s1.showstr();
cout << "len = " << s1.getstrlen() << endl;
s1.delchar('t');
s1.showstr();
cout << "len = " << s1.getstrlen() << endl;
s1.setstr(ns);
s1.showstr();
cout << "len = " << s1.getstrlen() << endl;
return 0;
}