字符指针和string的转换
1.string转换成char*:s1.c_str()//str()函数返回字符串的首地址。
2.字符串的拷贝:
string s1="aaavvv";
char buf1[128] ={0};//char buf[1024]={0}和char buf[1024]=""一样,因为'\0'字符的ASCII值为0,
s1.copy(buf1, 30, 0); //注意:只给你copy3个字符,后面不加‘\0’,所以在上面buf定义的时候可以加上={0},来避免后面乱码
cout << "buf1:" << buf1 << endl;
3.字符串的连接:
1.
string s1 = "aaa";
string s2 = "bbb";
s1 = s1 + s2;
cout << "s1:" << s1 << endl;
2.
string s3 = "333";
string s4 = "444";
s3.append(s4);
cout << "s3:" << s3 << endl;
4.字符串的查找和替换:
查找
int find(char c,int pos=0) const; //从pos开始查找字符c在当前字符串的位置
int find(const char *s, int pos=0) const; //从pos开始查找字符串s在当前字符串的位置
int find(const string &s, int pos=0) const; //从pos开始查找字符串s在当前字符串中的位置
find函数如果查找不到,就返回-1
int rfind(char c, int pos=npos) const; //从pos开始从后向前查找字符c在当前字符串中的位置
int rfind(const char *s, int pos=npos) const;
int rfind(const string &s, int pos=npos) const;
//rfind是反向查找的意思,如果查找不到, 返回-1
替换
string &replace(int pos, int n, const char *s);//删除从pos开始的n个字符,然后在pos处插入串s
string &replace(int pos, int n, const string &s); //删除从pos开始的n个字符,然后在pos处插入串s
void swap(string &s2); //交换当前字符串与s2的值
4.String的区间删除和插入
//在pos位置插入字符串s
string &insert(int pos, const char *s);
string &insert(int pos, const string &s);
string &insert(int pos, int n, char c); //在pos位置 插入n个字符c
string &erase(int pos=0, int n=npos); //删除pos开始的n个字符,返回修改后的字符串
string s1 = "hello1 hello2 hello1";
string::iterator it = find(s1.begin(), s1.end(), 'l');
if (it != s1.end() )
{
s1.erase(it);
}
cout << "s1删除l以后的结果:" << s1 << endl;
s1.erase(s1.begin(), s1.end() );
cout << "s1全部删除:" << s1 << endl;
cout << "s1长度 " << s1.length() << endl;
string s2 = "BBB";
s2.insert(0, "AAA"); // 头插
s2.insert(s2.length(), "CCC");//尾插
cout << s2 << endl;