C++STL之string类

最近在准备ccfcsp,于是学习了一下STL标准库的string类,在此记录。
作为STL类介绍的第一篇文章,首先简单介绍一下为什么要用STL,原因就是解决了一个问题之后,就不要对这个问题再来做重复的工作了,于是出现了模板。而宏定义由于不够安全,现在已经被STL取代。

引入 #include using std::string

构造函数

  • string name1(“aaa”);
  • string name2=“aaa”;
  • string name3(“aasdsadasdas”,9) 0-9个字符给name3
  • string name4(“sdasdas”,3,6) 最后一个参数6为最多复制多少个字符给name4,如果缺省则为从3后面的全部字符都给name4
  • string name5(‘d’,20) name5为20个字符d
  • 总结:string类的对象一般以()的形式初始化少用=,因为这样符合构造函数的形式。

运算符

  • =赋值运算
  • +连接运算
  • <、>等比较运算
  • 【】索引

成员函数

  • append 字符串连接 str.append(str1) str.append(str2,3,8) str2从3位置开始的八个字符进行连接
  • pushback 连接一个字符
  • compare str1.compare(str2) 返回类型为bool
  • clear 变为空字符串无返回值
  • empty 如果字符串为空返回true
  • find int pos1=str.find(str2,pos) 从0开始的pos位置开始找,否则从头开始。如果没有找到返回string::npos str.fing(ch,pos)查找一个字符
  • rfind 反向查找 str1.rfind(str2/ch,n)反向查找到正着开始数的弟n个字符
  • insert str1.insert(n1,str2,n2,n3)从str1的n1位置开始插入str2的n2位置开始的n3个字符
  • replace str1.replace(pos,n,str2,pos2,n2) replace(pos,n,ch)替换成字符
  • substr str1.substr(pos,n)
  • swap 交换函数
  • find_first_of int pos=str1.find_first_of(str3,n,m); n为从str1的哪个位置开始,m为str3的几个字符,参数可以为ch
  • find_first_not_of
  • find_last_of int pos=str1.find_first_of(str3);
  • find_last_not_of

迭代器

string::iterator it

  • it=str.begin(); 字符串的开始地址
  • it=str.end(); 字符串的最后一个地址在往后(字符串外的地址)

for(it=str.begin();it!=str.end();it++)

反向迭代器

string::reverse_iterator::it

  • rbegin()
  • rend()

此时it++实际为向左移动

补充如何实现字符串的反转

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
 
int main()
{
    string s = "hello";
 
    reverse(s.begin(),s.end());
 
    cout<<s<<endl;
 
    return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
 
int main()
{
    char s[]="hello";
 
    strrev(s);
 
    cout<<s<<endl;
 
    return 0;
}
发布了48 篇原创文章 · 获赞 23 · 访问量 1341

猜你喜欢

转载自blog.csdn.net/qq_37724465/article/details/91352597
今日推荐