1.构造函数
1.1函数接口
函数 | 含义 |
---|
string() | 构造空的string类对象 |
string(const char* s) | 用c_string来构造string类对象 |
string(size_t n,char c) | string类对象中包含n个字符c |
string(const string& s) | 拷贝构造函数 |
string(const string& s,size_t n) | 用s中的前n个字符构造新的string类对象 |
1.2函数接口用例
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
void TestString()
{
string s1;
string s2("hello");
string s3(5, 'b');
string s4(s3);
string s5(s4, 5);
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
cout << s4 << endl;
cout << s5 << endl;
}
int main()
{
TestString();
return 0;
}
2.容量操作函数
2.1 函数接口
函数 | 含义 |
---|
size_t size() const | 返回字符串有效字符长度 |
size_t length() const | 返回字符串有效字符长度 |
void clear | 清空有效字符 |
size_t capacity ( ) const | 返回空间总大小 |
bool empty ( ) const | 检测字符串释放为空串,是返回true,否则返回false |
void resize ( size_t n, char c ) | 将有效字符的个数该成n个,多出的空间用字符c填充 |
void resize ( size_t n ) | 将有效字符的个数改成n个,多出的空间用0填充 |
void reserve ( size_t res_arg=0 ) | 为字符串预留空间 |
2.2函数接口用例
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
void TestString()
{
string s1("hello");
cout << s1.size() << endl;
cout << s1.length() << endl;
cout << s1.capacity() << endl;
cout << s1.empty() << endl;
s1.clear();
cout << s1 << endl;
cout << s1.capacity() << endl;
string s2(5, 'a');
cout << s2.capacity() << endl;
s2.resize(10, 'b');
cout << s2 << endl;
cout << s2.capacity() << endl;
s2.resize(3);
cout << s2 << endl;
cout << s2.capacity() << endl;
}
void TestString2()
{
string s;
s.reserve(100);
cout << s.size() << endl;
cout << s.capacity() << endl;
s.reserve(50);
cout << s.size() << endl;
cout << s.capacity() << endl;
}
int main()
{
TestString2();
return 0;
}
3.修改函数
3.1 函数接口
函数 | 含义 |
---|
void push_back(char c) | 在字符串后尾插字符c |
string& append (const char* s) | 在字符串后追加一个字符串 |
string& operator+=(const string& str) | 在字符串后追加字符串str |
string& operator+=(const char* s) | 在字符串后追加C个数字符串 |
string& operator+=(char c) | 在字符串后追加字符c |
const char* c_str( ) const | 返回C格式字符串 |
size_t find (char c, size_t pos =0) const | 从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置 |
size_t rfind(char c, size_t pos = npos) | 从字符串pos位置开始往前找字符c,返回该字符在字符串中的位置 |
string substr(size_t pos = 0, size_t n= npos)const | 在str中从pos位置开始,截取n个字符,然后将其返回 |
3.2函数接口用例
#include <iostream>
#include <string>
using namespace std;
void TestString()
{
string str;
str.push_back(' ');
str.append("hello");
str += 'w';
str += "orld";
cout << str << endl;
cout << str.c_str() << endl;
string file1("test.cpp");
string file2("test.c.zip");
size_t pos = file1.rfind(".");
if (pos != string::npos)
{
string su(file1.substr(pos, file1.size() - 1));
cout << su << endl;
}
pos = file2.rfind(".");
if (pos != string::npos)
{
string su(file2.substr(pos, file2.size() - 1));
cout << su << endl;
}
}
int main()
{
TestString();
return 0;
}
4.string类对象的访问操作函数
4.1函数接口
函数 | 含义 |
---|
char& operator[] ( size_t pos ) | 返回pos位置的字符,const string类对象调用 |
const char& operator[] ( size_t pos ) const | 返回pos位置的字符,非const string类对象调用 |