string和char*的区别:
char*是一个指针
string是一个类,封装了char*,管理这个字符串,是char*的容器。
string() ; //空字符串
string(const char* s) ; //用字符串s初始化
string(const string& str) ; //拷贝构造
string(int n, char c) ; //用n个字符c初始化
string str1;
char s[12] = "hello world";
string str2(s);
string str3(str2);
string(10, 'a');
string& operator=(const char* s); //用字符串s赋值
string& operator=(const string& s); //用字符串s赋值
string& operator=(char c); //用字符c赋值
char s[12] = "hello world";
string str1 = s;
string str2 = str1;
string str3;
str3 = 'a';
string& assign(const char* s); //用字符串s赋值
string& assign(const char* s, int n); //用字符串s前n个字符赋值
string& assign(const string& s); //用字符串s赋值
string& assign(int n, char c); //用n个字符c赋值
string str1;
str1.assign("hello world");
str1.assign("hello world",5);
string str2;
str2.assign(str1);
str2.assign(10, 'a');
string& operator+= (const char* str) ;
string& operator+= (const char c) ;
string& operator+= (const string& str) ;
string str1 = "hello ";
str1 += "world";
str1 += '!';
string str2 = "haha ";
str1 += str2;
string& append(const char* s) ;
string& append(const char* s, int n) ; //把字符串s的前n个字符连接到当前字符串结尾
string& append(const string& s) ;
string& append(const string& s, int pos, int n) ;//字符串s从pos开始的n个字符连接到字符串结尾
(注:字符串下标从0开始)
string str1 = "hello";
str1.append(" ");
str1.append("world", 1);
string str2 = "or";
str1.append(str2);
str1.append("world", 3, 2);
cout << str1 << endl;
注:(1)查找函数返回值:找到返回位置,没找到返回 -1。
(2)rfind从右往左查找,find从左往右查找
string str1 = "abcdefg";
int pos = str1.find("de");//3
str1.replace(1, 2, "aa");
比较方式:逐个按ASCII码值进行对比。
=:返回 0
>:返回 1
<:返回 -1
int compare(const string& s) const;
cout << str[0] << endl;
int compare(const char* s) const;
string str1 = "abc";
string str2 = "abd";
cout << str1.compare(str2) << endl;
cout << str1.compare("abd") << endl;
cout << str[0] << endl;
char& at (int n);
cout << str.at(0) << endl;
string& insert (int pos, const char* s); //在指定位置插入字符串s
string& insert (int pos, const string& str); //在指定位置插入字符串s
string& insert (int pos, int n, char c); //在指定位置插入n个字符c
string& erase (int pos, int n = npos); //删除从pos开始的n个字符
string str1 = "world";
str1.insert(1, "111");
str1.erase(1, 3);
功能:从字符串中获取想要的子串。
string substr (int pos = 0, int n = npos) const; //返回由pos开始的n个字符组成的字符串
string str = "abcdef";
cout << str.substr(1, 3) << endl;