64,637
社区成员
发帖
与我相关
我的任务
分享
class String
{
public://构造与析构
String();//无参构造函数
String(char* tmp);//带参构造函数初始化
String(String& tmp);//拷贝构造函数
~String();//析构
public://属性
int get_length();//返回字符串长度
bool is_empty();//字符串是否为空
public://查找
int index(String& tmp);//寻找子串首次出现的位置
String substring(int p, int len);//从字符串中第p个位置开始(包括第p个字符)获取长度为len的子串
public://替换
void replace_char(char tmp_1, char tmp_2);//字符串中将字符tmp_1,替换成tmp_2
void replace_string(String& tmp_1, String& tmp_2);//字符串中将子串tmp_1,替换成子串tmp_2
public://插入
void insert_char(char c, int p);//在字符串第p个位置上插入字符c
void insert_string(String& tmp, int p);//在字符串第p个位置上插入字符串tmp
public://删除
void delete_string(int p, int len);//在字符串中第p个位置(包括第p个字母)开始删除长度为len的子串
public://运算符重载
friend ostream& operator << (ostream& os, String& tmp);
friend istream& operator >> (istream& is, String& tmp);
friend bool operator == (String& tmp_1, String& tmp_2);
friend bool operator != (String& tmp_1, String& tmp_2);
friend bool operator < (String& tmp_1, String& tmp_2);
friend bool operator > (String& tmp_1, String& tmp_2);
friend String operator + (String& tmp_1, String& tmp_2);//字符串连接
friend String operator - (String& tmp_1, String& tmp_2);//在tmp_1中删除所有其包含的子串tmp_2
void operator = (String& tmp);//String类的赋值
void operator = (char* tmp);//字符串的赋值
private:
List<char> string;
int length;
};
String operator+(String & tmp_1, String & tmp_2)
{
String temp;
for (tmp_1.string.point = tmp_1.string.head; tmp_1.string.point; tmp_1.string.point = tmp_1.string.point->next)
{
temp.string.addToTail(tmp_1.string.point->info);
temp.length++;
}
for (tmp_2.string.point = tmp_2.string.head; tmp_2.string.point; tmp_2.string.point = tmp_2.string.point->next)
{
temp.string.addToTail(tmp_2.string.point->info);
temp.length++;
}
return temp;
}
void String::operator=(String & tmp)
{
while (!string.isEmpty())
{
string.deleteFromHead();
}
for (tmp.string.point = tmp.string.head; tmp.string.point != NULL; tmp.string.point = tmp.string.point->next)
{
string.addToTail(tmp.string.point->info);
}
length = tmp.length;
}
String::String(String & tmp)
{
for (tmp.string.point = tmp.string.head; tmp.string.point; tmp.string.point = tmp.string.point->next)
{
string.addToTail(tmp.string.point->info);
length++;
}
}
#include <iostream>
#include "String.h"
using namespace std;
int main()
{
String aa(const_cast<char*>("Kevin"));
String bb(const_cast<char*>("Salvatore"));
String cc(const_cast<char*>("Kevin"));
String dd;
dd = aa + bb + cc;
system("pause");
return 0;
}
template<typename Temp>
class List
{
public:
Node<Temp> *head, *point, *tail;
List();
~List();
bool isEmpty();
void addToHead(Temp tmp);
void addToTail(Temp tmp);
Temp deleteFromHead();
Temp deleteFromTail();
void deleteNode(Temp tmp);
bool isInList(Temp tmp);
};