辐射4 居里 任务:我有一道编程难题 谁能帮帮我 谢谢

来源:百度文库 编辑:杭州交通信息网 时间:2024/04/29 14:02:22
定义一个字符串类STRING,使其至少有内容(CONTENTS)和长度(LENGTH)两个数据成员,并有显示符串,求字符串的长度,统计字符串数字字符的个数等功能。(要求写出构造函数和析构函数),给定字符串“gsadgasefs",先显示字符串,再求字符串的长度,最后统计数字字符的个数。要求:不能用库函数

在VC下建立一个空的控制台工程,工程名随便起。
在这个工程下建立3个文件:
stringClass.h //类的接口定义
stringClass.cpp //类的接口实现
test.cpp //测试这个类

///////stringClass.h的代码如下:
#ifndef STRINGCLASS_H
#define STRINGCLASS_H

class stringClass
{
public:
stringClass(char *s = ""); //构造函数
~stringClass(){delete str;} //析构函数
void displayStr() const; //显示串内容
int getLength() const; //取得串长
int NumericCharStat(); //统计串中数字的个数
private:
int length; //串长
char *str; //串内容
int strlength(char *s); //计算串长
};

#endif

///////stringClass.cpp的代码如下
#include <iostream>
#include "stringClass.h"

using namespace std;

stringClass::stringClass(char *s)
{
int i=0;
length = strlength(s);
str = new char [length];
while (i<length)
{
str[i]=s[i];
i++;
}
}

int stringClass::getLength() const
{
return length;
}

int stringClass::NumericCharStat()
{
int NumericNum=0;
int i=0;

while (i < length)
{
if(int(str[i]) >= 48 && int(str[i]) <= 57)
NumericNum++;
i++;
}

return NumericNum;
}

void stringClass::displayStr() const
{
cout<<"String Content is: "<<str<<endl;
}

int stringClass::strlength(char *s)
{
int i=0;
while (s[i]!='\0')
i++;
return i;
}

////////test.cpp的代码如下:
#include "stringClass.h"
#include <iostream>
using namespace std;

int main ()
{
stringClass myStr("gs67dgase0s");
myStr.displayStr();
cout<<"String Length is: "<<myStr.getLength()<<endl;
cout<<"There are "<<myStr.NumericCharStat()<<" number in the string."<<endl;

return 0;
}

/////////////////////////////////////
程序已经在VC++6.0下编译运行通过