#include "iostream"
using namespace std;
//#include "algorithm"
#include "string"
void main01()
{
//string 的初始化
string s1 = "zhangwentao";
string s2("liqimeng");
string s3(10, 'a');
//string 的遍历
//1 数组方式
for (int i = 0; i < s1.length(); i++)
{
cout << s1[i];
}
cout << endl;
//2 迭代器方式
for (string::iterator it = s1.begin(); it != s1.end(); it++)
{
cout << *it;
}
cout << endl;
for (int j = 0; j < s1.length(); j++)
{
cout << s1.at(j);
}
cout << endl;
//string 与字符指针的转化
printf("%s \n", s1.c_str()); //c_str()函数用来返回字符串首地址
char *buf = NULL;
buf = new char[50];
s1.copy(buf, 5, 0); //copy() 将string中的内容拷贝出来
buf[5] = '\0';
cout << "-----------" << endl;
cout << buf << endl;
delete[] buf;
buf = NULL;
//string 的连接
s3 = s1 + s2; //1 string类已经重载好了 = 运算符
cout << s3 << endl;
s1.append(s2); //2 使用append() 函数实现字符串连接
cout << s1 << endl;
}
void main02() //string 字符串的查找和替换
{
string s1 = "zhang sifh ah hello zhang jfk zhang";
int index = s1.find("zhang", 0);
cout << index << endl;
// 查找“zhang”出现的次数和出现的位置
int offindex = s1.find("zhang", 0);
while (1) //查找
{
if (offindex != string::npos)
{
cout << "offindex = " << offindex << endl;
offindex += 1;
offindex = s1.find("zhang", offindex);
}
else
{
break;
}
}
offindex = s1.find("zhang", 0);
while (1) // 替换
{
if (offindex != string::npos)
{
cout << "offindex = " << offindex << endl;
s1.replace(offindex, 5, "ZHANG");
offindex += 1;
offindex = s1.find("zhang", offindex);
}
else
{
break;
}
}
cout << "s1替换后:" << s1 << endl;
}
//
//void main03() //插入和删除
//{
// string s1 = "hello hello hello";
// cout << s1.length() << endl;
// string::iterator it = find(s1.begin(), s1.end(), "l");
// if (it != s1.end())
// {
// s1.erase(it);
// }
//
//}
void main()
{
// main01();
main02();
//();
system("pause");
}