??string是STL的字符串类型,通常用来表示字符串。而在使用string之前,字符串通常是用char*表示的。string与char*都可以用来表示字符串,那么二者有什么区别呢。
??string和char*的比较
int length() const; //返回当前字符串的长度。长度不包括字符串结尾的‘\0‘。
bool empty() const; //当前字符串是否为空
string &operator=(const string &s); //把字符串s赋给当前的字符串
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 &assign(const string &s,int start, int n); //把字符串s中从start开始的n个字符赋给当前字符串
string &operator+=(const string &s); //把字符串s连接到当前字符串结尾
string &operator+=(const char *s); //把字符串s连接到当前字符串结尾
string &append(const char *s); //把字符串s连接到当前字符串结尾
string &append(const char *s,int n); //把字符串s的前n个字符连接到当前字符串结尾
string &append(const string &s); //同operator+=()
string &append(const string &s,int pos, int n); //把字符串s中从pos开始的n个字符连接到当前字符串结尾
string &append(int n, char c); //在当前字符串结尾添加n个字符c
int compare(const string &s) const; //与字符串s比较
int compare(const char *s) const; //与字符串s比较
compare函数在>时返回 1,<时返回 -1,==时返回 0。比较区分大小写,比较时参考字典顺序,排越前面的越小。大写的A比小写的a小。
string substr(int pos=0, int n=npos) const; //返回由pos开始的n个字符组成的子字符串
void main25()
{
string s1 = "wbm hello wbm 111 wbm 222 wbm 333";
size_t index = s1.find("wbm", 0);
cout << "index: " << index;
//求itcast出现的次数
size_t offindex = s1.find("wbm", 0);
while (offindex != string::npos)
{
cout << "在下标index: " << offindex << "找到wbm\n";
offindex = offindex + 1;
offindex = s1.find("wbm", offindex);
}
//替换
string s2 = "wbm hello wbm 111 wbm 222 wbm 333";
s2.replace(0, 3, "wbm");
cout << s2 << endl;
//求itcast出现的次数
offindex = s2.find("wbm", 0);
while (offindex != string::npos)
{
cout << "在下标index: " << offindex << "找到wbm\n";
s2.replace(offindex, 3, "WBM");
offindex = offindex + 1;
offindex = s1.find("wbm", offindex);
}
cout << "替换以后的s2:" << s2 << endl;
}
string &insert(int pos, const char *s);
string &insert(int pos, const string &s);
//前两个函数在pos位置插入字符串s
string &insert(int pos, int n, char c); //在pos位置 插入n个字符c
string &erase(int pos=0, int n=npos); //删除pos开始的n个字符,返回修改后的字符串
void main27()
{
string s2 = "AAAbbb";
transform(s2.begin(), s2.end(), s2.begin(), toupper);
cout << s2 << endl;
string s3 = "AAAbbb";
transform(s3.begin(), s3.end(), s3.begin(), tolower);
cout << s3 << endl;
}
原文:https://www.cnblogs.com/tazimi/p/13310963.html