关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

【C++】string类接口的了解和使用(二)

发布时间:2023-06-29 13:00:19

举例说明:

void test6() {  //当n<size,不会缩容(删数据)   string s1("hello world");  s1.resize(4);  cout << s1.size() << endl;  cout << s1.capacity() << endl;  cout << s1 << endl << endl;   //当size<n<=capacity (插入数据)   string s2("hello world");  s2.resize(15, '#');  cout << s2.size() << endl;  cout << s2.capacity() << endl;  cout << s2 << endl << endl;   //当n>capacity, (扩容+插入数据)   string s3("hello world");  s3.resize(20, '#');  cout << s3.size() << endl;  cout << s3.capacity() << endl;  cout << s3 << endl << endl; }

   

所以resize功能还是比较完善健全的。

 4.operator[],at

 他们是一样的,都是读写到string中的某个值,进行操作。


但是区别在于:当发生越界时,operator[]会直接assert()报警告;而at则会抛异常(后面我们会详细了解)


5、Modifiers

1.push_back, append, operator+=

插入:

push_back :尾插

下面通过举例来观察: 

void test7() {  //push_back  string s1("hello world");  s1.push_back('x');  s1.push_back('y');  cout << s1 << endl;   //append  string s2("1111111111");  s2.append(s1);  cout << s2 << endl;  //operator+=  string s3("666");  s3 += ' ';  s3 += "hello world";  s3 += s2;  cout << s3 << endl; }

   

2.insert,erase

适用于头插,头删,中间插入和删除

但这两种函数我们都不建议经常使用,因为它的效率很低,在删除或者插入时,就会有数据挪动,效率很低。

void test8() {  string s("hello world");  s.insert(0, "bit");  cout << s << endl;   s.erase(0, 3);  cout << s << endl;   s.insert(5, "bit");  cout << s << endl;   s.erase(5,3);  cout << s << endl;   s.erase(5); //第二个参数不提供,默认是npos,直接从pos删到最后一个。  cout << s << endl; }

   

 3.assign,replace(不重要)

assign(功能):先clear,再赋值 

replace:替换内容

void test9() {  string s("3456789");  s.assign("1234");  cout << s << endl;   string s1("hello world");  s1.replace(6, 10, "666");  cout << s1; }

   

4.find,c_str,substr

find:也有缺省值,默认不提供,直接找到最后一个

c_str:取出C形式字符串(底层指针)

 

substr:取出str的一部分,再将其构建成新对象返回

getline:输入可以中间带空格的字符串

总结

这就是我们经常要用到的函数接口,更底层的内容,需要我们在模拟实现的时候,去好好感悟,下期再见!


/template/Home/leiyu/PC/Static