C++中的string类

一、构造函数

1.默认构造函数(defalut constructor):string()

2.指针拷贝构造函数(from c-string):string(const char* s)

3.拷贝构造函数(copy constructor):string(const string& str)

4.子串构造函数(substring constructor):string(const string& str, size_t pos, size_t len = npos)

npos的定义:static const size_t npos = -1,整型-1转换为无符号整型数表示size_t的最大值4,294,967,295。pos用于定位子串开始位置,len表示子串的长度,len的默认参数是npos,如果len值大于等于剩余子串长度或者没有提供len值,子串将直接取到str结尾。

5.指针限定拷贝构造函数(from buffer):string(const char* s. size_t n)

拷贝字符串的前n个字符

6.填充构造函数(fill constructor):string(size_t n, char c)

n个字符c构造成字符串

string s1;//默认构造函数
string s2("i love gjj");//指针拷贝构造函数
string s3(s2);//拷贝构造函数
string s4(s3, 7, 3);//子串构造函数
string s5("love from gjj", 4);//指针限定拷贝构造函数
string s6(10, '$');//填充构造函数

cout << s1 << endl;
cout << s2 << endl;//i love gjj
cout << s3 << endl;//i love gjj
cout << s4 << endl;//gjj
cout << s5 << endl;//love
cout << s6 << endl;//$$$$$$$$$$

二、赋值运算符重载

1.string& operator= (const string& str)

2.string& operator= (const char* s)

3.string& operator= (char c)

string s1, s2, s3;
s1 = "love from gjj";
s2 = s1;
s3 = 'j';

三、string类的访问

string类提供三种访问方法:下标+[ ]运算符重载、迭代器、范围for循环

1.下标+[ ]运算符重载

string s1("i miss gjj");
for (size_t i = 0; i < s1.size(); i++)
{
    cout << s1[i] << " ";
}
cout << endl;

2.迭代器 

//正向迭代器
string::iterator it1 = s1.begin();
while (it1 != s1.end())
{
    cout << *it1 << " ";
    ++it1;
}
cout << endl;

//反向迭代器
string::reverse_iterator rit = s1.rbegin();
while (rit != s1.rend())
{
    cout << *rit << " ";
    ++rit;
}
cout << endl;

3.范围for循环

for (auto e : s1)
{
    cout << e << " ";
}
cout << endl;
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

南林yan

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

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

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

打赏作者

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

抵扣说明:

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

余额充值