1. string类的初始化
string s1 = "abcd";
string s2("abcd");
string s3 = s2; //通过调用s3的拷贝构造函数来初始化对象s3
string s4 = (3, 'a'); //s4 = "aaa"
2. string类的遍历
string s1 = "helloworld";
//数组方式
for (int i = 0; i < s1.length(); ++i) {
cout << s[i] << endl;
}
//迭代器方式
for (string::iterator it = s1.begin(); it != s1.end(); ++it) {
cout << *it << endl;
}
for (int i = 0; i < s1.length() ++i) {
cout << s1.at(i) << endl; //与下标操作符[]对比,at能抛出异常
}
3. 字符指针和string类的转换
string s1 = "abcddd";
cout << "s1: %s" << s1.c_str();
char buf[128] = {'\0'};
s1.copy(p1, 3, 0); //从0个元素开始拷贝3个元素到p1的内存空间中,参数3默认值为0
cout << "buf = %s" << buf << endl; //打印abc
4. string类的连接
string s1 = "aaa";
string s2 = "bbb";
s1 = s1 + s2; //s1 = "aaabbb"
string s3 = "666";
string s4 = "777";
s3.append(s4); //s3 = "666777"
5. string类的查找和替换
string类关于查找和替换定义了如下诸多重载函数:
查找:
//从pos开始处查找字符c在当前字符串的位置(下标)
int find(char c, int pos = 0) const;
//从pos开始处查找字符串s在当前字符串的位置
int find(const char* s, int pos = 0) const;
//从pos开始处查找字符串s在当前字符串中的位置
int find(const string& s, int pos = 0) const;
//从pos开始处后面查找字符c在当前字符串的位置
int rfind(char c, int pos = npos) const;
//从pos开始处后面查找字符串s在当前字符串中的位置
int rfind(const char* s, int pos = npos) const;
//从pos开始处后面查找字符串s在当前字符串中的位置
int rfind(const string& s, int pos = npos) const;
替换:
//删除从pos开始处的n个字符,然后在pos处插入字符串s
string& replace(pos, int n, const char* s);
string& replace(int pos, int n, const string& s);
交换:
//交换当前字符串和s2的值
void swap(string& s2);
示例1:
string s1 = "abc hello abc world abc c/c++";
int index = s1.find("abc", 0);
while (index != string::npos) {
cout << "index = " << index << endl;
index += strlen("abc");
index = s1.find("abc", index);
}
示例2:
string s1 = "abc hello abc world abc c/c++";
index = s1.find("abc", 0);
while (index != string::npos) {
s1.replace(index, strlen("abc"), "___");
index += strlen("abc");
index = s1.find("abc", index);
}
cout << "s1 = " << s1 << endl;
6. string区间删除和插入
删除pos开始的n个字符,返回修改后的字符串:
string& erase(int pos = 0, int n);
示例1:
std::string str = "c_c++ java python go";
std::string::iterator it = find(str.begin(), str.end(), '_'); //find是stl算法的函数,需包含algorithm头文件。
if (it != str.end()) {
str.erase(it);
}
std::cout << str << std::endl;
str.erase(0, 5);
std::cout << str << std::endl;
在pos位置处插入字符串s:
string& insert(int pos, const char* s);
string& insert(intpos, const string& s);
在pos位置处插入n个字符c:
string& insert(int pos, int n, char c);
示例2:
std::string str2 = "world";
str2.insert(0, "hello");
std::cout << str2 << std::endl;