C++实现String类

实现一个String类

String类原型:
class String
{
private:
    char * str;             // pointer to string
    int len;                // length of string
    static int num_strings; // String类对象数量
    static const int CINLIM = 80;  // cin input limit	输入限制
};
需要实现的功能:
  1. 实现char*和String类的构造,提供无参构造
  2. 实现=,[],>,<,==,<<,>>,运算符重载
  3. 功能函数
函数名功能
append将字符添加到字符串的末尾。
assign将字符添加到字符串的末尾。
at返回对字符串中指定位置的元素的引用。
begin返回一个迭代器,寻址字符串中的第一个元素。
c_str将字符串的内容转换为C样式,以null终止的字符串。
capacity返回在不增加字符串的内存分配的情况下可以存储在字符串中的最大元素数。
cbegin返回一个指向字符串中第一个元素的const迭代器。
cend返回一个常量迭代器,该迭代器可寻址字符串中最后一个元素之后的位置。
clear擦除字符串的所有元素。
compare将字符串与指定字符串进行比较,以确定两个字符串是否相等,或者在字典上小于另一个。
copy从源字符串中的索引位置最多复制指定数量的字符到目标字符数组。
crbegin返回一个常量迭代器,该迭代器处理反向字符串中的第一个元素。
crend返回一个常量迭代器,该迭代器寻址反向字符串中最后一个元素之后的位置。
data将字符串的内容转换为字符数组。
empty测试字符串是否包含字符。
end返回一个迭代器,该迭代器寻址字符串中最后一个元素之后的位置。
erase从指定位置删除字符串中的一个元素或元素范围。
find在向前方向的字符串中搜索与指定字符序列匹配的子字符串的首次出现。
front返回对字符串中第一个元素的引用。
insert在字符串中的指定位置插入一个或多个元素或一系列元素。
length返回字符串中的当前元素数。
max_size返回字符串可以包含的最大字符数。
pop_back擦除字符串的最后一个元素。
push_back在字符串末尾添加一个元素。
rbegin返回一个迭代器,该迭代器返回反向字符串中的第一个元素。
rend返回一个迭代器,该迭代器指向恰好超出反向字符串中最后一个元素的位置。
replace将指定位置的字符串中的元素替换为指定字符或从其他范围或字符串或C字符串复制的字符。
reserve将字符串的容量设置为至少等于指定数字的数字。
resize指定字符串的新大小,并根据需要添加或删除元素。
rfind向后搜索字符串,查找与指定字符序列匹配的子字符串的首次出现。
size返回字符串中的当前元素数。
substr从指定位置开始的字符串中复制最多包含一些字符的子字符串。
swap交换两个字符串的内容。

String类示例:

// string1.h -- fixed and augmented string class definition

#ifndef STRING_H_
#define STRING_H_
#include <iostream>
using std::ostream;
using std::istream;

class String
{
private:
    char * str;             // pointer to string
    int len;                // length of string
    static int num_strings; // String类对象数量
    static const int CINLIM = 80;  // cin input limit	输入限制
public:
// constructors and other methods
    String(const char * s); // constructor
    String();               // default constructor
    String(const String &); // copy constructor
    ~String();              // destructor
    int length () const { return len; }
	int size() const { return len; }
// overloaded operator methods    
    String & operator=(const String &);
    String & operator=(const char *);
    char & operator[](int i);
    const char & operator[](int i) const;
	String & operator+(const String &st);
	String & operator+(const char *s);
// overloaded operator friends
    friend bool operator<(const String &st, const String &st2);
    friend bool operator>(const String &st1, const String &st2);
    friend bool operator==(const String &st, const String &st2);
	friend bool operator==(const String &st, const char *st2);
    friend ostream & operator<<(ostream & os, const String & st);
    friend istream & operator>>(istream & is, String & st);
// static function
    static int HowMany();
public:
	//功能函数
	void append(const String &st);	//追加字符串
	void append(const char*s);		//追加字符串

	void push_back(const char ch);	//追加字符
	void swap(char* s);				//交换值
	void swap(String& st);			//交换值
	int find(const char*s, size_t index);	//寻找字符串
	int find(const String&st, size_t index);//寻找字符串
};
#endif
// string1.cpp -- String class methods
#include <cstring>                 // string.h for some
#include "string.h"               // includes <iostream>
using std::cin;
using std::cout;

// initializing static class member

int String::num_strings = 0;

// static method
int String::HowMany()
{
    return num_strings;
}

void String::append(const String & st)
{
	strcat(this->str, st.str);
	this->len = strlen(this->str);
	return;
}

void String::append(const char * s)
{
	strcat(this->str, s);
	this->len = strlen(this->str);
	return;
}

void String::push_back(const char ch)
{
	strcat(this->str, &ch);
	this->len = strlen(this->str);
	return;
}

void String::swap(char * s)
{
	char temp[CINLIM];
	strcpy(temp, this->str);
	strcpy(this->str,s);
	strcpy(s, temp);
	this->len = strlen(this->str);
	return;
}

void String::swap(String & st)
{
	char temp[CINLIM];
	strcpy(temp, this->str);
	strcpy(this->str, st.str);
	strcpy(st.str, temp);
	this->len = strlen(this->str);
	st.len = strlen(st.str);
	return;
}

int String::find(const char * s, size_t index)
{
	int length = strlen(s);
	for (int this_index = index; this_index < this->len; this_index++)
	{
		if (this->str[this_index] == s[0])
		{
			for (int s_index = 0; s_index < length; s_index++)
			{
				if (this->str[this_index + s_index] != s[s_index])
					break;
				if (s_index == length - 1)	//匹配字符串
					return this_index;
			}
		}
	}
	return -1;
}

int String::find(const String & st, size_t index)
{
	int length = strlen(st.str);
	for (int this_index = index; this_index < this->len; this_index++)
	{
		if (this->str[this_index] == st.str[0])
		{
			for (int s_index = 0; s_index < length; s_index++)
			{
				if (this->str[this_index + s_index] != st.str[s_index])
					break;
				if (s_index == length - 1)	//匹配字符串
					return this_index;
			}
		}
	}
	return -1;
}

// class methods
String::String(const char * s)     // construct String from C string
{
    len = std::strlen(s);          // set size
    str = new char[len + 1];       // allot storage
    std::strcpy(str, s);           // initialize pointer
    num_strings++;                 // set object count
}

String::String()                   // default constructor
{
    len = 4;
    str = new char[1];
    str[0] = '\0';                 // default string
    num_strings++;
}

String::String(const String & st)
{
    num_strings++;             // handle static member update
    len = st.len;              // same length
    str = new char [len + 1];  // allot space
    std::strcpy(str, st.str);  // copy string to new location
}

String::~String()                     // necessary destructor
{
    --num_strings;                    // required
    delete [] str;                    // required
}

// overloaded operator methods    

// assign a String to a String
String & String::operator=(const String & st)
{
    if (this == &st)
        return *this;
    delete [] str;
    len = st.len;
    str = new char[len + 1];
    std::strcpy(str, st.str);
    return *this;
}

// assign a C string to a String
String & String::operator=(const char * s)
{
    delete [] str;
    len = std::strlen(s);
    str = new char[len + 1];
    std::strcpy(str, s);
    return *this;
}

// read-write char access for non-const String
char & String::operator[](int i)
{
    return str[i];
}

// read-only char access for const String
const char & String::operator[](int i) const
{
    return str[i];
}

String & String::operator+(const String & st)
{
	// TODO: 在此处插入 return 语句
	strcat(this->str, st.str);
	return *this;
}

String & String::operator+(const char * s)
{
	// TODO: 在此处插入 return 语句
	strcat(this->str, s);
	return *this;
}

// overloaded operator friends

bool operator<(const String &st1, const String &st2)
{
    return (std::strcmp(st1.str, st2.str) < 0);
}

bool operator>(const String &st1, const String &st2)
{
    return st2 < st1;
}

bool operator==(const String &st1, const String &st2)
{
    return (std::strcmp(st1.str, st2.str) == 0);
}

bool operator==(const String & st, const char * st2)
{
	return (strcmp(st.str, st2) == 0);
}

// simple String output
ostream & operator<<(ostream & os, const String & st)
{
    os << st.str;
    return os; 
}

    // quick and dirty String input
istream & operator>>(istream & is, String & st)
{
    char temp[String::CINLIM];
    is.get(temp, String::CINLIM);
    if (is)
        st = temp;
    while (is && is.get() != '\n')
        continue;
    return is; 
}
测试代码:
//main.cpp
#include<iostream>
#include"string.h"
int main()
{
	String s1 = "123";
	String s2("abc");
	String* s3 = new String("xyz");
	//赋值
	s1 = s2;   //相比C strcpy 更方便
	//比较
	if (s1 == s2)
	{
		cout << "s1 = s2" << endl;
	}
	cout << "===========拼接字符串============" << endl;
	s1 = s1 + "456";
	cout << s1 << endl;
	s1.append("789");
	cout << s1 << endl;
	s1.push_back('!');
	cout << s1 << endl;
	//交换
	cout << s1 << " " << s2 << endl;
	cout << "===========交换字符串============" << endl;
	s1.swap(s2);
	cout << s1 << " " << s2 << endl;
	//字符串长度
	cout << s2.size() << endl;
	//查找 替换

	cout << "===========寻找字符串============" << endl << s2.find("456", 0) << endl;
	cin.get();
	return 0;
}
测试结果:
s1 = s2
===========拼接字符串============
abc456
abc456789
abc456789!
abc456789! abc
===========交换字符串============
abc abc456789!
10
===========寻找字符串============
3
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DeRoy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值