string容器的基本语法

本文详细介绍了C++中string容器的初始化、赋值、拼接、查找与替换、比较、字符存取、插入和删除等基本操作,以及如何获取和操作子串。通过实例展示了每个操作的方法和效果,帮助读者深入理解C++字符串处理。
摘要由CSDN通过智能技术生成

string容器

初始化

string str1="hello world";
string str2("hello world");
string str3(str2);
string str4(4,'n');//str4是由4个n组成
string str5='x';

赋值

与初始化很相似。

string str1="hello world";
string str2(str1);//
string str3.assign("hello world");
string str4.assign("hello world",5)//将hello world的前五个字符对str4赋值
string str5.assign(str4);

拼接

 //第一种
string str1="我喜欢";
string str2="打篮球!";
str1+=str2;
cout<<str1<<endl;//即 我喜欢打篮球!
//第二种
string str3="I ";
str3.append("love you");//append
cout<<str3<<endl;//即 I love you
//第三种
string str4="i love ";
str4.append("game abcd",4);//取前四个
cout<<str4<<endl;//即i love game

查找和替换

//查找
//find
string str1="abcdefg";
int a=str1.find("de");//找de在字符串中的位置
cout<<a<<endl;//结果即为3
//rfind
string str2="abcdefgde";
int a=str2.rfind("de");//找位置
cout<<a<<endl;//结果即为7
//二者的区别:find从左往右, rfind从右往左,但最后显示的下标数都是从左到右
//替换
string str3="abcdef";
str3.replace(1,3,"1111");//从一号位置起三个字符即bcd替换为1111
cout<<str3<<endl;//结果即a1111ef

比较

//逐个字符进行比较
string str1="hello";
string str2="zello";
if(str1.compare(str2)<0)
{
    cout<<"str1小于str2"<<endl;
}

字符存取

string str1="hello";
for(int i=0;i<str1.size();i++)
{
    cout<<str1[i]<<endl;//或者使用at,即为下一行代码
    cout<<str1.at(i)<<endl;
}
//修改
str1[0]='o';
cout<<str1<<endl;//或者用at的方式进行修改

插入和删除

//插入
string str="hello";
str.insert(1,"hi");
cout<<"str="<<str<<endl;//此时输出的是hhiello
//删除
str.erase(1,3);
cout<<"str="<<str<<endl;//此时输出的便是hello

string子串

在字符串中截取想要的子串

string str1="hello";
string str2=str1.substr(1,3);//从下标为1的位置截取三个
cout<<"str2="<<str2<<endl;//结果即为ell
//举例
string str3="qiqi@163.com";//截取用户信息
int m=str3.find('@');
string str4=str3.substr(0,m);
cout<<str4<<endl;//结果即为qiqi
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值