#define _SCL_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
void main21()
{
string s1 = "aaaa";
string s2("bbbbb");
string s3 = s2;
string s4(10, 'a');
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
cout << s4 << endl;
}
void main22()
{
string s1 = "asdf";
try
{
for (int i = 0; i < s1.length(); i++)
{
cout << s1[i] << " ";//[]不会抛异常
}
}
catch (...)
{
cout << "发生异常1!" << endl;
}
for (string::iterator it = s1.begin(); it != s1.end(); it++)
{
cout << *it << " ";
}
try
{
for (int i = 0; i < s1.length(); i++)
{
cout << s1.at(i) << " ";//at可以抛异常
}
}
catch (...)
{
cout << "发生异常2!" << endl;
}
}
//字符指针的string的转换
void main23()
{
string s1 = "aaaasdf";//char*===>string
//s1===>char *
cout << s1.c_str() << endl;
//s1 的内容copy 到buf中
char buf1[20] = {0};
s1.copy(buf1, 3,0);//只给你copy3个字符,不会变成C风格的字符串。从0的位置开始拷贝
cout << buf1 << endl;
}
//字符串的连接
void main24()
{
string s1 = "aaa";
string s2 = "bbb";
s1 = s1 + s2;
cout << s1 << endl;
string s3 = "3333";
string s4 = "4444";
s3.append(s4);
cout << s3 << endl;
}
//字符串的替换和查找
void main25()
{
string s1 = "bmw 111 bmw 222 bmw 333 bmw 555";
int index = s1.find("bmw", 0);
cout << index << endl;
//案例1 求bmw出现的次数 每一次出现的数组下标
int offindex = s1.find("bmw", 0);
while (offindex != string::npos)
{
cout << "index:" << offindex << endl;
offindex += 1;
offindex = s1.find("bmw", offindex);
}
int offindex2 = s1.find("bmw", 0);
while (offindex2 != string::npos)
{
s1.replace(offindex2, 1, "BMWW");//案例2 从offindex2位置开始替换1个字符,替换为“BMW”
offindex2 += 1;
offindex2 = s1.find("bmw", offindex2);
}
cout << s1 << endl;
}
//删除字符
void main26()
{
string s1 = "hello1 hello2 world";
string::iterator it = find(s1.begin(), s1.end(), 'h');
if (it != s1.end())
{
s1.erase(it);
}
cout << s1 << endl;
s1.erase(s1.begin(), s1.end());//全部删除
cout << s1 << s1.length() << endl;
s1.insert(0, "AAA");//在头部插入AAA
s1.insert(s1.length(), "CCC");//在尾部插入CCC
cout << s1 << endl;
}
//转换大小写
void main27()
{
string s1 = "AAAbbb";
string s2 = "aaaBBB";
transform(s1.begin(), s1.end(), s1.begin(), toupper);
transform(s2.begin(), s2.end(), s2.begin(), tolower);
cout << s1 << endl;
cout << s2 << endl;
}
void main()
{
main27();
}
String的简单应用
最新推荐文章于 2020-12-04 19:41:17 发布