> 文章列表 > string容器

string容器

string容器

1、string的构造和赋值

string容器
string容器

#include
#include
using namespace std;

void test01()
{
string str1(“hello world”); //使用字符串初始化
cout<<str1<<endl;
string str2(5,‘A’); //使用 n 个字符串是初始化
cout<<str2<<endl;
string str3 = str2; //拷贝构造,是两个类型相同的对象
cout<<str3<<endl;

string str4; //无参构造
str4 = “hello world”; //赋值运算
cout<<str4<<endl;
str4 = ‘W’; //str4指向的空间被释放掉,根本不用我们管,所以str4重新指向 'w’所在的空间
cout<<str4<<endl;

str4.assign(“hello world”, 5); //任何容器只要有 assing这个方法,都叫赋值,这个是成员函数赋值
cout<<str4<<endl;
str4.assign(str1, 2, 3); //成员函数赋值
cout<<str4<<endl;
}
int main(int argc, char *argv[])
{
test01();
return 0;
}

string容器

2、string存取字符操作

string容器
void test02()
{
string str1=“hello world”;
cout<<str1[1]<<" "<<str1.at(1)<<endl;
str1[1]=‘E’; //数组形式
str1.at(6)=‘H’; //成员函数
cout<<str1<<endl;

//[] 越界不会抛出异常 at越界会抛出异常
try
{
str1[1000]=‘A’;
str1.at(1000)=‘A’;
}
catch(exception &e)
{
cout<<“捕获到异常:”<<e.what()<<endl;
}
}

int main(int argc, char *argv[])
{
test02();
return 0;
}
string容器

3、string拼接操作

string容器
void test03()
{
string str1=“hello”;
str1 += “world”; //字符串拼接
cout<<str1<<endl;

string str2=“hehe”;
str1 += str2;
cout<<str1<<endl;

string str3=“hello”;
string str4=“world”;
cout<<str3+str4<<endl;

string str5=“hello”;
string str6=“world”;
str5.append(str6, 2, 3);
cout<<str5<<endl;
str5.append(“world”, 3);
cout<<str5<<endl;
}

int main(int argc, char *argv[])
{
test03();
return 0;
}
string容器

4、字符串查找

string容器
查找网站 ip 地址中的所有的字符串 sex,并对字符串 sex 进行替换

void test04()
{
string str1=“http://www.sex.777.sex.999.sex.com”;
while(1)
{
int ret = str1.find(“sex”);
if(ret == -1)
break;

str1.replace(ret,3,“***”);
}

cout<<str1<<endl;
}

int main(int argc, char *argv[])
{
test04();
return 0;
}
string容器

4、字符串比较

void test05()
{
string str1 =“hehe”;
string str2 = “haha”;
if(str1.compare(str2) > 0 )
{
cout<<“大于”<<endl;
}
else if(str1.compare(str2) == 0)
{
cout<<“等于”<<endl;
}
else if(str1.compare(str2) < 0)
{
cout<<“小于”<<endl;
}
}

int main(int argc, char *argv[])
{
test05();
return 0;
}

string容器

5、字符串提取

将ip地址中的每一个字符串按照 : 提取

void test06()
{
string str1=“hehehe:hahaha:xixixi:lalala”;
int pos = 0; //记录子串的初始位置
while(1)
{
int ret = str1.find(“:”, pos); //从初始位置 0 开始查找 :的下标记并录位置
if(ret < 0) //查询lalala子串是否含有 :
{
string tmp = str1.substr(pos, str1.size()-pos);
cout<<tmp<<endl;
break;
}

string tmp = str1.substr(pos, ret-pos); //提取子串的宽度
cout<<tmp<<endl;

pos = ret+1; //提取一个子串之后的字符的起始位置
}
}

int main(int argc, char *argv[])
{
test06();
return 0;
}
string容器

6、插入和删除操作

string容器

精明眼电影影评