C++ 提供的 string 类包含了若干实用的成员函数,大大方便了字符串的增加、删除、更改、查询等操作。
插入字符串
insert() 函数可以在 string 字符串中指定的位置插入另一个字符串,它的一种原型为:
string& insert (size_t pos, const string& str);
pos 表示要插入的位置,也就是下标;str 表示要插入的字符串,它可以是 string 变量,也可以是C风格的字符串。
请看下面的代码:
#include <iostream> #include <string> using namespace std; int main(){ string s1, s2, s3; s1 = s2 = "1234567890"; s3 = "aaa"; s1.insert(5, s3); cout<< s1 <<endl; s2.insert(5, "bbb"); cout<< s2 <<endl; return 0; }
insert() 函数的第一个参数有越界的可能,如果越界,则会产生运行时异常,后续我会讲解如何捕获这个异常。
删除字符串
erase() 函数可以删除 string 变量中的一个子字符串。它的一种原型为:
string& erase (size_t pos = 0, size_t len = npos);
pos 表示要删除的子字符串的起始下标,len 表示要删除子字符串的长度。如果不指明 len 的话,那么直接删除从 pos 到字符串结束处的所有字符