在学习c++的过程中。 想到使用C++的类实现一个 类似于JavaScript 字符串的 slice 函数
mystring.h
#ifndef MYSTRING_H
#define MYSTRING_H
#include <iostream>
using namespace std;
class MyString {
public:
MyString(const char *); // 有参构造
MyString (const MyString&); //拷贝构造
MyString slice(int); //切割字符串函数
MyString slice(int,int); //切割字符串函数
void operator=(char *); // 重载=
void operator=(MyString&); // 重载 =
char &operator[](int); // 重载[]
~MyString(); // 析构函数
char * get_value(); // 获取字符串的值
private:
char * string;
int size_of;
};
ostream & operator<<(ostream &cout,MyString &str);
#endif // MYSTRING_H
mystring.cpp
#include <iostream>
#include <mystring.h>
#include <string.h>
#include <stdlib.h>
// 运算符重载
ostream & operator<<(ostream &cout,MyString &str)
{
cout<<str.get_value();
return cout;
}
void MyString::operator=(char *str)
{
if(this->string!=NULL){
delete []this->string;
this->string=NULL;
}
this->string= new char[strlen(str)+1];
strcpy(this->string,str);
this->size_of=strlen(this->string);
}
void MyString::operator=(MyString &str)
{
if(this->string!=NULL){
delete []this->string;
this->string=NULL;
}
this->string= new char[strlen(str.get_value())+1];
strcpy(this->string,str.get_value());
this->size_of=strlen(this->string);
}
char &MyString::operator[](int len)
{
return this->string[len];
}
// 构造函数 有参构造和拷贝构造
MyString::MyString(const char *str)
{
this->string =new char[strlen(str)+1];
strcpy(this->string,str);
this->size_of=strlen(str);
}
MyString::MyString(const MyString&str)
{
this->string = new char[strlen(str.string)+1];
strcpy(this->string,str.string);
this->size_of= strlen(this->string);
}
// 析构函数
MyString::~MyString()
{
delete []this->string;
}
// 切割字符串函数 从指定下标开始到最后一位。返回新的字符串
MyString MyString::slice(int num)
{
// 切割字符串 返回一个新的字符串
int len = this->size_of-num;
char *str=new char [len];
int j = 0;
for (int i = num ; i <this->size_of;i++) {
str[j]=this->string[i];
j++;
}
return MyString (str) ;
}
// 切割字符串函数重载 从指定下标开始到指定下标结束。 返回新的字符串
MyString MyString::slice(int start,int end)
{
// 切割字符串 返回一个新的字符串
if(end<0 ){
// 截取到最后一个
return this->slice(start);
}else if(end<start){
// 结束小于起始
return MyString("");
}else {
if(end >this->size_of){
end = this->size_of;
}
int len = end-start;
char *str=new char [len];
int j = 0;
for (int i = start ; i <=end;i++) {
str[j]=this->string[i];
j++;
}
return MyString (str);
}
}
char * MyString::get_value()
{
return (this->string);
}
main.cpp
#include <iostream>
#include <mystring.h>
#include <string>
void test(){
MyString baseStr("0123456789");
MyString baseStr1 = "1234657890" ;
MyString baseStr2 =MyString(baseStr) ;
cout<<baseStr<<endl; // 0123456789
cout<<baseStr1<<endl; // 1234657890
cout<<baseStr2<<endl; // 0123456789
baseStr[0]='a';
cout<<baseStr<<endl; // a123456789
MyString test1 = baseStr.slice(3);
MyString test2 =baseStr1.slice(4,100);
MyString test3 =baseStr2.slice(4,5);
cout<<test1<<endl; // 3456789
cout<<test2<<endl; // 657890
cout<<test3<<endl; // 45
}
int main()
{
test();
return 0;
}