STL容器:string类的简介与使用

传统的C

  1. 没有专门的字符串类型,需要使用常量字符串或者字符数组来使用
  2. 在实际运用中,一般使用字符串函数来处理

string类基本操作

  1. string是表示字符串的字符串类
  2. 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作
  3. string在底层实际是:basic_string模板类的别名
    typedef basic_string<char, char_traits, allocator> string;
  4. 不能操作多字节或者变长字符的序列
  5. 在使用string类时,必须包含#include<string>以及using namespace std;

string类对象的常见构造

函数名称功能说明
string()构造空的string类对象,即空字符串
string(const char* s)用C-string来构造string类对象
string(size_t n, char c)string类对象中包含n个字符c
string(const string& s)拷贝构造函数
void TestString()
{
    string s1; // 构造空的string类对象s1
    string s2("hello world"); // 用C格式字符串构造string类对象s2
    string s3(s2); // 拷贝构造s3
}

string类对象的容量操作

函数名称功能说明
size返回字符串有效字符长度
length返回字符串有效字符长度
capacity返回空间总大小
empty检测字符串释放为空串,是返回true,否则返回false
clear清空有效字符
reserve为字符串预留空间即扩容
resize将有效字符的个数该成n个,多出的空间用字符c填充
//size、length、capacity、resize
void TestString()
{
    string s("hello,world!");
    cout << s.size() << endl;
    cout << s.length() << endl;
    cout << s.capacity() << endl;
    cout << s << endl;

    //将s中的字符串清空,注意清空时只是将size清0,不改变底层空间的大小
    s.clear();
    cout << s.size() << endl;
    cout << s.capacity() << endl;

    //将s中有效字符个数增加到10个,多出位置用'a'进行填充
    //"aaaaaaaaaa"
    s.resize(10, 'a');
    cout << s.size() << endl;
    cout << s.capacity() << endl;
    cout << s << endl;

    //将s中有效字符个数增加到15个,多出位置用缺省值'\0'进行填充
    //"aaaaaaaaaa\0\0\0\0\0"
    //注意此时s中有效字符个数已经增加到15个
    s.resize(15);
    cout << s.size() << endl;
    cout << s.capacity() << endl;
    cout << s << endl;

    //将s中有效字符个数缩小到5个
    s.resize(5);
    cout << s.size() << endl;
    cout << s.capacity() << endl;
    cout << s << endl;
}

注意:

  1. size()与length()方法底层实现原理完全相同,引入size()的原因是为了与其他容器的接口保持一致,一般情况下基本都是用size()。
  2. clear()只是将string中有效字符清空,不改变底层空间大小。
  3. resize(size_t n) 与 resize(size_t n, char c)都是将字符串中有效字符个数改变到n个,不同的是当字符个数增多时:resize(n)用\0来填充多出的元素空间,resize(size_t n, char c)用字符c来填充多出的元素空间。注意:resize在改变元素个数时,如果是将元素个数增多,可能会改变底层容量的大小,如果是将元素个数减少,底层空间总大小不变。
  4. reserve(size_t res_arg=0):为string预留空间,不改变有效元素个数,当reserve的参数小于string的底层空间总大小时,reserve不会改变容量大小。

string类对象的访问及遍历操作

函数名称功能说明
operator[]返回pos位置的字符
begin + endbegin获取第一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器
rbegin + rendrbegin返回指向字符串的最后一个字符的反向迭代器 + rend返回指向字符串的第一个字符前一个位置的反向迭代器
范围forC++11支持更简洁的范围for的新遍历方式
void TestString1()
{
    string s1("hello world");
    const string s2("Hello World");
    cout << s1 << " " << s2 << endl;
    cout << s1[0] << " " << s2[0] << endl;

    s1[0] = 'H';
    cout << s1 << endl;

    //编译失败,因为const类型对象不能修改
    //s2[0] = 'h';
}
void TestString2()
{
    string s("hello world");
    // 3种遍历方式:
    // 需要注意的以下三种方式除了遍历string对象,还可以遍历是修改string中的字符
    // 且以下三种方式对于string而言,第一种使用最多

    // 1. for+operator[]
    for (size_t i = 0; i < s.size(); ++i)
    {
        cout << s[i];
    }
    cout << endl;

    // 2.迭代器
    string::iterator it = s.begin();
    while (it != s.end())
    {
        cout << *it;
        ++it;
    }
    cout << endl;

    // 反向迭代器
    string::reverse_iterator rit = s.rbegin();
    while (rit != s.rend())
    {
        cout << *rit;
        ++rit;
    }
    cout << endl;
        
    // 3.范围for
    for (auto ch : s)
    {
        cout << ch;
    }
    cout << endl;
}

string类对象的修改操作

函数名称功能说明
push_back在字符串后尾插字符c
append在字符串后追加一个字符串
operator+=在字符串后追加字符串str
c_str返回C格式字符串
find + npos从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置
rfind从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置
substr在str中从pos位置开始,截取n个字符,然后将其返回
void TestString()
{
    string str;
    str.push_back(' ');  // 在str后插入空格
    str.append("hello"); // 在str后追加一个字符"hello"
    str += 'w';          // 在str后追加一个字符'w'
    str += "orld";       // 在str后追加一个字符串"orld"
    cout << str << endl;
    cout << str.c_str() << endl; // 以C语言的方式打印字符串

    // 获取file的后缀
    string file("string.cpp");
    size_t pos = file.rfind('.');
    string suffix(file.substr(pos, file.size() - pos));
    cout << suffix << endl;

    // npos是string里面的一个静态成员变量
    // static const size_t npos = -1;

    // 取出url中的域名
    string url("http://www.cplusplus.com/reference/string/string/find/");
    cout << url << endl;
    size_t start = url.find("://");
    if (start == string::npos)
    {
        cout << "invalid url" << endl;
        return;
    }
    start += 3;
    size_t finish = url.find('/', start);
    string address = url.substr(start, finish - start);
    cout << address << endl;

    // 删除url的协议前缀
    pos = url.find("://");
    url.erase(0, pos + 3);
    cout << url << endl;
}

注意:

  1. 在string尾部追加字符时,s.push_back(c); s.append(1, c); s += 'c'三种的实现方式差不多,一般情况下string类的+=操作用的比较多,+=操作不仅可以连接单个字符,还可以连接字符串。
  2. 对string操作时,如果能够大概预估到放多少字符,可以先通过reserve把空间预留好。

string类非成员函数

函数名称功能说明
operator+尽量少用,因为传值返回,导致深拷贝效率低
operator>>输入运算符重载
operator<<输出运算符重载
getline获取一行字符串

string类深浅拷贝

浅拷贝
string浅拷贝
上述string类没有显式定义其拷贝构造函数与赋值运算符重载,此时编译器会合成默认的,当用s1构造s2时,编译器会调用默认的拷贝构造。最终导致的问题是,s1、s2共用同一块内存空间,在释放时同一块空间被释放多次而引起程序崩溃,这种拷贝方式,称为浅拷贝。

深拷贝
如果一个类中涉及到资源的管理,其拷贝构造函数、赋值运算符重载以及析构函数必须要显式给出。一般情况都是按照深拷贝方式提供。
string深拷贝

简单的模拟实现string类(造轮子)

只考虑深浅拷贝。

传统写法

namespace MakeString
{
	class string
	{
	public:
		string(const char* str = "")
			: _str(new char[strlen(str) + 1])
		{
			strcpy(_str, str);
		}

		~string()
		{
			delete[] _str;
			_str = nullptr;
		}

		string(const string& s)
			: _str(new char[strlen(s._str) + 1])
		{
			strcpy(_str, s._str);
		}

		string& operator=(const string& s)
		{
			if (this != &s)
			{
				delete[] _str;
				_str = new char[strlen(s._str) + 1];
				strcpy(_str, s._str);
				return *this;
			}
		}

		char& operator[](size_t index)
		{
			return _str[index];
		}

		const char& operator[](size_t index) const
		{
			return _str[index];
		}

		const char* c_str() const
		{
			return _str;
		}

		const size_t size() const
		{
			return strlen(_str);
		}

	private:
		char* _str;
	};
}

现代写法

namespace MakeString
{
	class string
	{
	public:
		string(const char* str = "")
			: _str(new char[strlen(str) + 1])
		{
			strcpy(_str, str);
		}

		~string()
		{
			delete[] _str;
			_str = nullptr;
		}

		string(const string& s)
		{
			_str = nullptr;
			string tmp(s._str); //调用构造函数
			std::swap(_str, tmp._str);
		}

		string& operator=(string s)
		{
			std::swap(_str, s._str);
			return *this;
		}

		char& operator[](size_t index)
		{
			return _str[index];
		}

		const char& operator[](size_t index) const
		{
			return _str[index];
		}

		const char* c_str() const
		{
			return _str;
		}

		const size_t size() const
		{
			return strlen(_str);
		}

	private:
		char* _str;
	};
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值