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

简介: 【C++】string类接口的了解和使用

举例说明:

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:输入可以中间带空格的字符串

总结

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

目录
相关文章
|
1天前
|
C语言 C++ 容器
C++ string类
C++ string类
8 0
|
1天前
|
C++ Linux
|
1天前
|
编译器 C++
【C++】继续学习 string类 吧
首先不得不说的是由于历史原因,string的接口多达130多个,简直冗杂… 所以学习过程中,我们只需要选取常用的,好用的来进行使用即可(有种垃圾堆里翻美食的感觉)
7 1
|
1天前
|
设计模式 安全 算法
【C++入门到精通】特殊类的设计 | 单例模式 [ C++入门 ]
【C++入门到精通】特殊类的设计 | 单例模式 [ C++入门 ]
17 0
|
1天前
|
C语言 C++
【C++】string类(常用接口)
【C++】string类(常用接口)
21 1
|
1天前
|
算法 安全 程序员
【C++】STL学习之旅——初识STL,认识string类
现在我正式开始学习STL,这让我期待好久了,一想到不用手撕链表,手搓堆栈,心里非常爽
16 0
|
1天前
|
存储 安全 测试技术
【C++】string学习 — 手搓string类项目
C++ 的 string 类是 C++ 标准库中提供的一个用于处理字符串的类。它在 C++ 的历史中扮演了重要的角色,为字符串处理提供了更加方便、高效的方法。
16 0
【C++】string学习 — 手搓string类项目
|
1天前
|
Java C++ Python
【C++从练气到飞升】06---重识类和对象(二)
【C++从练气到飞升】06---重识类和对象(二)
|
1天前
|
编译器 C++
【C++从练气到飞升】06---重识类和对象(一)
【C++从练气到飞升】06---重识类和对象(一)