#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");
}