#include<bits/stdc++.h>
using namespace std;
int main()
{
string str1;
str1="hello";
cout<<str1<<endl;
string str2;
str2=str1;
cout<<str2<<endl;
string str3;
str3.assign("hello",2);//输出字符串的前2位
cout<<str3<<endl;
//字符串拼接 +
string str4;
str4=str1+str2;
cout<<str4<<endl;//hellohello
string str5="I";
str5.append("love");
str5.append("you 778",3);//I LOVE YOU
cout<<str5<<endl;
str5.append(str1,0,1);//截取str1中从0到一 截取可自定义 (s,a,b)a指从哪开始接,b表示截取的个数
cout<<str5<<endl;
//查找和替换
string s1="abcdef";
//find()是从左向右查
int pos=s1.find("de");
cout<<pos<<endl;//3 返回de第一次出现的位置0 1 2 3 无返回-1
//if(pos== -1)cout<<"未找到"<<endl; else cout<<post;
//rfind()是从右向做查
pos=s1.rfind("de");
cout<<pos<<endl;//3
//replace替换 从一号起 ,把连续三个位置替换成111
s1.replace(1,3,"111");//1-b
cout<<s1<<endl;
//compare字符串比较
string s2="xello";
string s3="hello";
if(s2.compare(s3)==0)
{
cout<<"="<<endl;
}
//字符存取
string s4="hello";
//读 实现字符串中单个元素输出1【】2at
for(int i=0;i<s4.size();i++)
{
cout<<s4[i]<<" ";
}
cout<<endl;
//写 改元素
s4[0]='y';
cout<<s4<<endl;
//插入和删除
string a="hello";
//插入insert
a.insert(1,"yyy");
cout<<a<<endl;
//删除
a.erase(1,2);
cout<<a<<endl;
//截取想要字符串
string b="abcdef";
string sub=b.substr(1,3);
cout<<sub<<endl;//bcd
// 重点从邮件中截取用户名
string email="zhangsan@163.com";
pos=email.find("@");
string username=email.substr(0,pos);
cout<<username<<endl; //zhangsan
return 0;
}
#include<string>容器
最新推荐文章于 2024-07-14 15:36:20 发布