String用法
作者:
gzcoder
,
2021-09-28 11:17:35
,
所有人可见
,
阅读 239
#include<iostream>
#include<string>
using namespace std;
void test01()//构造函数
{
string s1;
cout<<"s1 = "<<s1<<endl;
const char * str="hello world!";
string s2(str);
cout<<"s2 = "<<s2<<endl;
string s3(s2);
cout<<"s3 = "<<s3<<endl;
string s4(10,'a');
cout<<"s4 = "<<s4<<endl;
}
void test02()//string 赋值操作
{
string s1;
s1="hello";
cout<<"s1 = "<<s1<<endl;
string s2;
s2=s1;
cout<<"s2 = "<<s2<<endl;
string s3;
s3='a';
cout<<"s3 = "<<s3<<endl;
string s4;
s4.assign("hello c++");
cout<<"s4 = "<<s4<<endl;
string s5;
s5.assign("hello c++",5);
cout<<"s5 = "<<s5<<endl;
string s6;
s6.assign(s5);
cout<<"s6 = "<<s6<<endl;
string s7;
s7.assign(10,'w');
cout<<"s7 = "<<s7<<endl;
}
void test03()//字符串拼接
{
string s1;
string s2;
s1.assign("hello ");
s2.assign("c++");
//s1+=s2;
//s1+="world";
//s1+='w';
//s1.append("world",2);
//s1.append(s2);
//s1.append(s2,1);
cout<<"s1 = "<<s1<<endl;
}
void test04()//字符串查找
{
string str1="abcdefgde";
int pos = str1.find("de");
if(pos == -1)
cout<<"未找到字符串"<<endl;
else
cout<<"找到字符串,pos = "<<pos<<endl;
//rfind
//rfind从右往左查找 find从左往右查找
pos=str1.rfind("de");
cout<<"pos ="<<pos<<endl;
}
void test05()//字符串替换
{
string str1 = "abcdefg";
//从1号位置起3个字符替换为“1111”
str1.replace(1,3,"1111");
cout<<"str1 = "<<str1<<endl;
}
void test06()//字符串比较
{
string str1 = "xello";
string str2 = "hello";
int ret = str1.compare(str2);
if(ret == 0)
cout<<"str1 等于 str2"<<endl;
else if(ret > 0)
cout<<"str1 大于 str2"<<endl;
else
cout<<"str1 小于 str2"<<endl;
}
void test07()//字符串存取
{
string str1 = "hello";
//通过[]访问
for(int i = 0; i < str1.size(); i++)
cout<<"str["<<i<<"] = "<<str1[i]<<endl;
cout<<"--------------"<<endl;
//通过at方式访问
for(int i = 0; i < str1.size(); i++)
cout<<"str["<<i<<"] = "<<str1.at(i)<<endl;
cout<<"--------------"<<endl;
//修改
str1[0]='x';
cout<<"str1[0] = "<<str1[0]<<endl;
str1.at(0)='h';
cout<<"str1[0] = "<<str1.at(0)<<endl;
}
void test08()//字符串插入和删除
{
string s1="hello";
//插入
s1.insert(1,"111");
cout<<"s1 = "<<s1<<endl;
s1.insert(1,3,'a');
cout<<"s1 = "<<s1<<endl;
//删除
s1.erase(1,3);
cout<<"s1 = "<<s1<<endl;
s1.erase(1,3);
cout<<"s1 = "<<s1<<endl;
}
void test09()//子串
{
string str = "abcdef";
string sub=str.substr(1,3);
cout<<"sub = "<<sub<<endl;
//实用操作
string email = "zhangsan@sina.com";
//从邮件地址中 获取 用户名信息
int len=email.find('@');
sub = email.substr(0,len);
cout<<"用户名 = "<<sub<<endl;
}
int main()
{
//test01();//构造函数
//test02();//赋值操作
//test03();//拼接
//test04();//查找
//test05();//替换
//test06();//比较
//test07();//存取
//test08();//插入和删除
test09();//子串
return 0;
}