本质:
string和char*区别:
特点:
string类内部封装了很多成员方法 例如: 查找find,拷贝copy,删除delete 替换replace,插入insertstring管理char*所分配的内存,不用担心复制越界和取值越界等,由类内部进行负责
如何用string构造字符串
构造函数原型:
string s1;//默认构造
const char* str="hello world";
string s2(str);
cout<<s2<<endl;
string s3(s2);
cout<<s3<<endl;
string s4(10,'a');
功能描述:
赋值的函数原型:
int main()
{
string str1;
str1 = "hello";
cout <<"str1=" << str1 << endl;
string str2;
str2 = str1;
cout << "str2=" << str2 << endl;
string str3;
str3 = 'a';
cout << "str3=" << str3 << endl;
string str4;
str4.assign("hello world");
cout << "str4=" << str4 << endl;
string str5;
str5.assign("hello world",5);
cout << "str5=" << str5 << endl;
string str6;
str6.assign(10, 'a');
cout << "str6=" << str6 << endl;
return 0;
}
功能描述:
函数原型:
int main()
{
string str1="hello ";
cout << "str1=" << str1 << endl;
str1 += "world";
cout << "str1=" << str1 << endl;
str1 += ';';
cout << "str1=" << str1 << endl;
string str2 = "pubg";
str1 += str2;
cout << "str1=" << str1 << endl;
string str3="I";
cout << "str3=" << str3 << endl;
str3.append(" love ");
cout << "str3=" << str3 << endl;
str3.append("game abd", 4);
cout << "str3=" << str3 << endl;
//str3.append(str2);
//cout << "str3=" << str3 << endl;
//str1=hello world;pubg
str3.append(str1, 12, 4);//只截取到pubg 参数2是从哪个位置开始截取,参数3是截取字符个数
cout << "str3=" << str3 << endl;
return 0;
}
功能描述:
函数原型:
注意:rfind从右往左查
find从左往右查
//字符串查找和替换
//查找
void test1()
{
string str1 = "abcdefgde";
int pos=str1.find("de");//从第一个字符开始找,存在则返回第一个字符的下标,不存在就返回-1
cout << pos << endl;
//rfind从右往左查
//find从左往右查
pos=str1.rfind("de");
cout << pos << endl;
}
//替换
void test2()
{
string str1 = "abcdefg";
//从下标为1的位置起三个字符替换为“1111”
//去掉bcd ,插入“1111”
str1.replace(1, 3, "1111");
cout << str1 << endl;
}
int main()
{
//test1();
test2();
return 0;
}
功能描述:
比较方式:
= 返回 0 > 返回 1 < 返回 -1 函数原型:
//string字符串比较
int main()
{
string str1 = "hello";
string str2 = "hello";
if (str1.compare(str2) == 0)
{
cout << "str1==str2" << endl;
}
string str3 = "ok";
if (str1.compare(str3) < 0)
{
cout << "str1<str3" << endl;
}
return 0;
}
string中单个字符存取方式有两种
//string字符存取
int main()
{
string str = "hello world";
//通过[]访问单个字符
for (int i = 0; i < str.size(); i++)
{
cout << str[i] << " ";
}
cout << endl;
//通过at访问单个字符
for (int i = 0; i < str.size(); i++)
{
cout << str.at(i) << " ";
}
cout << endl;
//修改单个字符
str[0] = 'x';
cout << str << endl;
str.at(0) = 'p';
cout << str << endl;
return 0;
}
功能描述:
函数原型:
//string的插入和删除
int main()
{
string str = "hello";
//起始下标都是0
//插入
str.insert(1, "111");//在指定位置之前插入
cout << str << endl;
//删除
str.erase(1, 3);//从指定位置开始删除多少个
cout << str << endl;
return 0;
}
功能描述:
函数原型:
//string子串
int main()
{
string str = "abcdef";
string subStr = str.substr(1, 3);//从某个位置开始截取多少个
cout << "subStr=" << subStr << endl;
string email = "wzh@qq.com";
int pos = email.find("@");
string s = email.substr(0, pos);
cout << s <<endl;
return 0;
}