简单实现string
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
class myString
{
private:
// 私有属性
char *str;
int size;
public:
// 无参构造
myString() : size(32)
{
str = new char[size];
strcpy(str, "");
}
// 有参构造
myString(const char *s)
{
size = strlen(s);
str = new char[size + 1];
strcpy(str,s);
cout<<"str="<<str<<endl;
}
//拷贝构造(深拷贝)
myString(myString &other):str(new char(*(other.str))),size(other.size){
strcpy(str,other.str);
}
//析构函数
~myString(){
delete str;
}
//判空函数
bool isEmpty(){
if(strlen(str)>0){
return false;
}else if (strlen(str)==0) {
return true;
}
return false;
}
//size函数
int strSize(){
return size;
}
//c_str函数
char * c_str(){
return str;
}
//at函数
char &strAt(int index){
if(index<0||index>size){
cout<<"下标不合法!";
return str[0];
}
return str[index];
}
};
int main()
{
char input[30]="";
int index;
cout<<"请输入一个字符串"<<endl;
//获取字符串
fgets(input,sizeof(input),stdin);
//getline(cin,input);
//初始化
myString str(input);
//拷贝
myString strcp(str);
//判空
cout<<"判空:"<<boolalpha<<strcp.isEmpty()<<endl;
//获取大小
cout<<"大小:"<<strcp.strSize()<<endl;
//c_str
printf("str=%s\n",strcp.c_str());
//at函数
cout<<"请输入字符串下标"<<endl;
cin>>index;
cout<<str.strAt(index)<<endl;
return 0;
}
现象: