string使用方法

# include <iostream>
# include <string>


using namespace std;


void test01()
{
string s1;//调用无参构造
string s2(10, 'a');
string s3("abcdefg");
string s4(s3);//拷贝构造


cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
cout << s4 << endl;
}


//赋值操作
void  test02()
{
string s1;
string s2("appp");
s1 = "abcdef";
cout << s1 << endl;
s1 = s2;
cout  << s1 << endl;
s1 = 'a';
cout << s1 << endl;


//成员函数方法
//assign赋值操作
s1.assign("jkl");
cout << s1 << endl;
}
//取值操作
void test03()
{
string s1 = "abcdefg";


//重载[]操作符
for(int i = 0; i < s1.size(); i++)
{
cout << s1[i] << " ";
}
cout << endl;


//at成员函数
for(int i = 0; i < s1.size(); i++)
{
cout << s1.at(i)<< " ";
}
cout << endl;


//区别:[]如果访问越界,直接挂掉
//at方式访问越界会抛异常out_of_range


try
{
cout << s1.at(100)<< endl;
}
catch(...)
{
cout << "越界" << endl;
}

}
//拼接操作
//append加到尾部
void test04()
{
string s = "abcd";
string s2 = "1111";
s += "abcd";
s += s2;


cout << s << endl;


string s3 = "2222";
s2.append(s3);
cout << s2 << endl;
string s4 = s2 + s3;
cout << s4 << endl;


}


//查找和替换
//find从前往后
//rfind从后往前
void test05()
{
string s = "abcdefghjfgkl";
//查找第一次出现的位置
int pos = s.find("fg");
cout << "pos = " << pos << endl;
//查找最后一次出现的位置
pos = s.rfind("fg");
cout << "pos = " << pos << endl;
}


//string替换
void test06()
{
string s = "abcdefg";
s.replace(1, 2, "111");
cout << s << endl;
}


//string比较
//compare >返回1 < 返回-1 =返回0
void test07()
{
string s1 = "abcd";
string s2 = "abce";


if(s1.compare(s2) == 0)
{
cout << "字符串相等" << endl;
}
else
{
cout << "字符串不相等" << endl;
}
}


//子串操作
void test08()
{
string s = "abcdefg";
string mysubstr = s.substr(1, 3);
cout << mysubstr << endl;
}


//插入操作和删除操作
void test09()
{
string s = "abcdefg";
s.erase();
cout << s << endl;
s.insert(3, "111");//前面插
cout << s << endl;


s.erase(0, 1);//把1之前的都删除1保留
cout << s << endl;
}


int main(int argc, char *argv[])
{
//test01();
//test02();
// test03();
//test04();
test05();
//test06();
//test07();
//test08();
//test09();
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值