string类对象

本文详细介绍了C++中的String类,包括常用构造方法(如空字符串、C-string构造和拷贝构造)、容量操作(如size(),empty(),clear(),reserve(),resize()),以及访问和遍历字符串的方式([]运算符和迭代器的使用)。
摘要由CSDN通过智能技术生成


String类

(1) 常用接口–string 对象的常见构造

int main()
{
	string s0;	// 构造空的string类对象,即空字符串
	string s1("hello world");	// 使用C-string 构造string类对象
	string s2(s1);	// 拷贝构造

	// 从s2 第4个位置的索引处开始,连续10个字符,组成的字符串构造string类对象。
	// 如果指定长度10大于从索引位置到字符串结尾的长度,则直接到字符串结尾。 
	string s3(s2, 4, 10);
	// 如果不指定长度,则到字符串结尾。
	string s4(s2, 4);
	// 如果指定长度小于从索引位置到字符串结尾的长度,且指定长度大于等于0,则按实际长度。
	string s5(s2, 4, 0);
	// 如果指定长度为负数,则从索引处到字符串结尾。
	string s6(s2, 4, -2);

	int i = 0;
	cout << i++ << "->" << s0 << endl;
	cout << i++ << "->" << s1 << endl;
	cout << i++ << "->" << s2 << endl;
	cout << i++ << "->" << s3 << endl;
	cout << i++ << "->" << s4 << endl;
	cout << i++ << "->" << s5 << endl;
	cout << i++ << "->" << s6 << endl;

	return 0;
}

(2) string对象的容量操作

  • size (重点)返回字符串有效长度(不包含‘\0’)
  • length 返回字符串有效长度(不包含‘\0’),和size相同,推荐使用size;
  • capacity 返回空间总大小
  • empty (重点)检测字符串释放为空串,是返回true, 否返回false
  • clear (重点)清空有效字符, 不改变底层空间。
  • reserve(重点)为字符串预留空间
  • resize(重点)将有效字符的个数改成n个,多出的空间用字符c 填充

(3) string 对象的访问及遍历

class String
{
public:
    // [] 运算符重载
	char& operator[](size_t pos)
	{
		return _str[pos];
	}

private:
	char* _str;
	size_t _size;
	size_t _capacity;
};
  • [ i ] 遍历。底层原理是operator[] 的操作符重载

    string s("hello world");
    for (int i=0; i<s.size(); ++i)
    {
    	cout << s[i] << " ";
    }
    cout << endl;
    
    
  • 迭代器iterator

    string::iterator it = s.begin();
    while (it != s.end())
    {
    	cout << *it << " ";
    	++it;
    }
    cout << endl;
    
  •   // 正向迭代器
      iterator begin();
      iterator end();
      
      // 反向迭代器
      reverse_iterator rbegin();
      reverse_iterator rend();
      
      // const 迭代器
      const_iterator begin() const;
      const_iterator end() const;
    
  • 范围for, 底层原理是迭代器

    for (auto e : s)
    {
        cout << e << " ";
    }
    cout << endl;
    
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值