针对CCF第三题总结C++STL的一些函数说明

针对CCF第三题总结C++STL的一些函数说明

本文的依据来自网络,难免存在错误或侵权,大家可以指出,共同进步。

string

string是C++对C的字符数组的扩展,使用起来更方便。要想使用标准C++中string类,必须要包含

#include<>string> //注意是<string>,不是<string.h>
  1. 声明
string s;//声明一个string 对象
string ss[10];//声明一个string对象的数组
  1. 构造方法(初始化)
#include <bits/stdc++.h>
using namespace std;

int main()
{
   
    ios::sync_with_stdio(false);cin.tie(0);
    string s;//默认初始化,一个空字符串
    string s1("ssss");//s1是字面值“ssss”的副本
    cout<<"s1:"<<s1<<endl;
    string s2(s1);//s2是s1的副本
    cout<<"s2:"<<s2<<endl;
    string s3=s2;//s3是s2的副本
    cout<<"s3:"<<s3<<endl;
    string s4(3,'c');//把s4初始化为3个'c'组成的字符串"ccc"
    cout<<"s4:"<<s4<<endl;
    string s5="hiya";//拷贝初始化
    cout<<"s5:"<<s5<<endl;
    string s6=string(10,'c');//拷贝初始化,生成一个初始化好的对象,拷贝给s6
	cout<<"s6:"<<s6<<endl;
    //string s(cp,n)
    char cs[]="12345";
    string s7(cs,3);//复制字符串cs的前3个字符到s当中
	cout<<"s7:"<<s7<<endl;
    //string s(s2,pos2)
    string s8="asac";
    string s9(s8,2);//从s8的下标为2处开始拷贝,下标不能超过s8的size
	cout<<"s9:"<<s9<<endl;
    //string s(s2,pos2,len2)
    string s10="qweqweqweq";
    string s11(s10,3,4);//s11是s19从下标3开始4个字符的拷贝,下标不能超过s10.size
    cout<<"s11:"<<s11<<endl;
    return 0;
}

本地运行图

  1. string类的字符串处理:

substr:获取子串

注意substr没有迭代器作为参数的操作,都是以下标为参数的。

#include <bits/stdc++.h>
using namespace std;
int main()
{
   
    ios::sync_with_stdio(false);cin.tie(0);
    string s="abcdefg";

    //s.substr(pos1,n)返回字符串位置为pos1后面的n个字符组成的串
    string s2=s.substr(1,5);//bcdef

    //s.substr(pos)//得到一个pos到结尾的串
    string s3=s.substr(4);//efg

    return 0;
}

本地运行图

insert:插入操作

注意用迭代器当参数和无符号数当参数的区别。
用无符号数时,是1~str.size()
用迭代器时,主要用str.begin(),str.end()两个首尾迭代器来标记位置
ps:有关迭代器的声明、使用见下文

#include <bits/stdc++.h>
using namespace std;
int main()
{
   
    ios::sync_with_stdio(false);
    string str="to be question";
    string str2="the ";
    string str3="or not to be";
    string::iterator it;

    //s.insert(pos,str)//在s的pos位置插入str
    str.insert(6,str2);                 // to be the question
	cout<<"str:"<<str<<endl;
    //s.insert(pos,str,a,n)在s的pos位置插入str中插入位置a到后面的n个字符
    str.insert(6,str3,3,4);             // to be not the question
	cout<<"str:"<<str<<endl;
    //s.insert(pos,cstr,n)//在pos位置插入cstr字符串从开始到后面的n个字符
    str.insert(10,"that is cool",8);    // to be not that is the question
	cout<<"str:"<<str<<endl;
    //s.insert(pos,cstr)在s的pos位置插入cstr
    str.insert(10,"to be ");            // to be not to be that is the question
	cout<<"str:"<<str<<endl;
    //s.insert(pos,n,ch)在s.pos位置上面插入n个ch
    str.insert(15,1,':');               
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值