string容器概念
- char*是一个指针,string是一个类,string封装了char*,管理这个字符串,是一个char*型的容器
- string封装了许多实用的成员方法,例如查找find,拷贝copy,删除delete,替换,插入等等
- 不用考虑内存释放和越界,string管理char*所分配的内存,每一次string的复制,取值都由string类负责维护,不用担心复制越界和取值越界等
- string和char*可以相互转换
- s.at(i)和s[i]的区别在于s.at(i)若越界会抛出异常out_of_range
String常用的API
string拼接操作
string& operator+=(const string& str);
string& operator+=(const char* str);
string& operator+=(const char c);
string& append(const char *s);
string& append(const char *s,int n);
string& append(const string &s);
string& append(const string &s,int pos,int n);
string& append(int n,char c);
string查找和替换
int find(const string& str,int pos=0) const;
int find(const char* s,int pos=0) const;
int find(const char *s,int pos,int n) const;
int find(const char c,int pos=0) const;
int rfind(const string& str,int pos=npos) const;
int rfind(const char* s,int pos=npos) const;
int rfind(const char* s,int pos,int n) const;
int rfind(const char c,int pos=0)const;
string& replace(int pos,int n,const string& str);
string& replace(int pos,int n,const char* s);
string比较操作
- compare函数在>0时返回1,<0时返回-1,==时返回0
- 比较区分大小写,参考字典顺序,排前面越小,大写比小写的要小
int compare(const string &s) const;
int compare(const char *s) const;
获取string子串操作
string substr(int pos=0,int n=npos) const;
插入和删除操作
string& insert(int pos,const char* s);
string& insert(int pos,const string& str);
string& insert(int pos,int n,char c);
string& erase(int pos,int n=npos);
小结
代码案例
#include<iostream>
#include<string>
using namespace std;
void test01()
{
string s1;
string s2(10, 'a');
string s3("abcdefg");
string s4(s3);
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
cout << s4 << endl;
}
void test02()
{
string s1;
string s2("appp");
s1 = "abcdef";
cout << s1 << endl;
s1 = s2;
cout << s1 << endl;
s1 = 'a';
cout << s1 << endl;
s1.assign("jkl");
cout << s1 << endl;
}
void test03()
{
string s1 = "abcdef";
for (int i = 0; i < s1.size(); i++)
{
cout << s1[i] << " ";
}
cout << endl;
for (int i = 0; i < s1.size(); i++)
{
cout << s1.at(i) << " ";
}
cout << endl;
try
{
cout << s1.at(100) << endl;
}
catch (...)
{
cout << "越界" << endl;
}
}
void test04()
{
string s1 = "abcd";
string s2 = "1111";
s1 += "asd";
s1 += s2;
cout << s1 << endl;
string s3 = "2222";
s2.append(s3);
cout << s2 << endl;
string s4 = s2 + s3;
cout << s4 << endl;
}
void test05()
{
string s = "abcdefghifgjkl";
int pos = s.find("fg");
cout << "pos:" << pos << endl;
pos = s.rfind("fg");
cout << "pos:" << pos << endl;
}
void test06()
{
string s = "abcdeg";
s.replace(0, 0, "123");
cout << s << endl;
}
void test07()
{
string s1 = "abcd";
string s2 = "abce";
int k;
if (( k=s1.compare(s2))==0)
{
cout << "字符串相等" << endl;
}
else
{
cout << "字符串不相等" << endl;
}
}
void test08()
{
string s1 = "zbcdefg";
string s2 = s1.substr(1, 3);
cout << s2 << endl;
}
void test09()
{
string s = "abcdefg";
s.insert(3, "123");
cout << s << endl;
}
int main(void)
{
test09();
return 0;
}