STL基础笔记之string

#include<iostream>
#include<string>
using namespace std;
void test01()//str.at(i),[]越界直接挂掉
{
    string str = "hello word";
    for (int i = 0; i < str.size(); i++)
    {
        cout << str[i] << endl;
    }
    for (int i = 0; i < str.size(); i++)
    {
        cout << str.at(i) << endl;
    }
    //try
    //{
    //    cout << str[100] << endl;
    //}
    //catch (...)//扑捉异常 
    //{
    //    cout << "越界异常" << endl;//结果是没有捕捉异常
    //}
    try
    {
        cout << str.at(100) << endl;
    }
    catch (...)//扑捉异常
    {
        cout << "越界异常" << endl;
    }//结果是  "越界异常" 
}
int main()
{
    test01();
    system("pause");
}
#include<iostream>
#include<string>
using namespace std;
void test01()//字符串的拼接
{
	string str1 = "abc";
	string str2 = "efg";
	str1 += str2;
	cout << str1<<endl;//结果:abcefg
	str1.append("hij");//追加
	cout << str1<<endl;//结果:abcefghij
	
}
void test02()//字符串的查找
{
	string str1 = "abcebfg";
	int pos=str1.find("b");
	cout << "b的位置是:" << pos << endl;//b的位置是:1,找不到返回-1
	int pos2 = str1.rfind("b");//从尾部开始查找
	cout << "b的位置是:" << pos2 << endl;//b的位置是:4
	//字符串的替换
	string str3= "abcebfg";
	str3.replace(1,3,"1112");
	cout << "replace of  str3" << str3 << endl;//replace of  str3a1112bfg
}
int main()
{
	test01();
	test02();
	system("pause");
}
#include<iostream>
#include<string>
using namespace std;
void test01()//字符串的比较
{
	string str1 = "abc";
	string str2 = "abcd";
	if (str1.compare(str2)==0)
	{
		cout << "str1==str2" << endl;
	}
	else if (str1.compare(str2) == 1)
	{
		cout << "str1>str2" << endl;
	}
	else
	{
		cout << "str1<str2" << endl;
	}
	//str1<str2
}
//string子串
void test02()
{
	string s1 = "abcde";
	string s2 = s1.substr(1,3);
	cout << "s2子串" << s2 << endl;//s2子串bcd
	//假如要找到邮件的用户名
	string email = "cuishenghui@sina.com";
	int pos = email.find("@");
	string name = email.substr(0, pos);
	cout << "name:" << name << endl;//name:cuishenghui
}
//子串的删除和插入
void test03()
{
	string  str1 = "hello";
	str1.insert(1,"123");
	cout << "str1.insert:" << str1<<endl;//str1.insert:h123ello
	//删除
	str1.erase(1, 2);
	cout << "str1.erase:" << str1 << endl;//h3ello
}
int main()
{
	test01();
	test02();
	test03();
	system("pause");
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值