目录
- string():生成空字符串;
- string (const string& str):生成str字符串的一个拷贝;
- string (const string& str, size_t pos, size_t len = npos):生成str字符串pos位置字符开始,npos个字符的拷贝(如果数量不足,则到结尾为止);
- string (const char* s):生成字符数组s的一个拷贝;
- string (const char* s, size_t n):生成字符数组s前n个元素的一个拷贝;
- string (size_t n, char c):生成有n个字符c的一个字符串;
- template
string (InputIterator first, InputIterator last): 利用迭代器生成字符串;
- size():返回string对象的字符个数;
- capacity():重新分配内存之前,string对象能包含的最大字符数;
- reserve(size_t n = 0):修改string的容量为n,若n大于现有容量,则不进行改变;
- resize(size_t n, char c):修改string的字符个数,若n小于现有字符个数,对其进行截断,若n大于现有字符串个数,使用字符c进行填充;
C ++字符串支持常见的比较操作符(>,>=,<,<=,==,!=),甚至支持string与C-string的比较(如 str<”hello”)。
在使用>,>=,<,<=这些操作符的时候是根据“当前字符特性”将字符按字典顺序进行逐一得比较。字典排序靠前的字符小,比较的顺序是从前向后比较,遇到不相等的字符就按这个位置上的两个字符的比较结果确定两个字符串的大小(前面减后面)。
- 使用[ ]:string支持使用[ ]进行类似于数组的随机访问;
- 使用at(size_t pos):类似与[ ],区别为at函数会进行越界检查;
- 迭代器与反向迭代器
- push_back(char c):尾插;
- insert(iterator pos, char c):在pos位置前插入字符c;
- void test()
- {
- string s1;
-
- // 尾插一个字符
- s1.push_back('a');
- s1.push_back('b');
- s1.push_back('c');
- cout<<"s1:"<<s1<<endl; // s1:abc
-
- // 在pos前插入字符c
- s1.insert(s1.begin(),'1');
- cout<<"s1:"<<s1<<endl; // s1:1abc
- }
- append()
- +=操作符
- void test()
- {
- // 方法一
- string s1("abc");
- s1.append("def");
- cout<<"s1:"<<s1<<endl; // s1:abcdef
-
- // 方法二
- string s2 = "abc";
- s2 += "def";
- cout<<"s2:"<<s2<<endl; // s2:abcdef
- }
- iterator erase(iterator p):删除字符串中p所指的字符
- iterator erase(iterator first, iterator last):删除字符串中迭代器区间[first,last)上所有字符
- string& erase(size_t pos = 0, size_t len = npos):删除字符串中从索引位置pos开始的len个字符
- void clear():/删除字符串中所有字符
- size_t find (constchar* s, size_t pos = 0) const:在当前字符串的pos索引位置开始,查找子串s,返回找到的位置索引,-1表示查找不到子串;
- size_t find (charc, size_t pos = 0) const:在当前字符串的pos索引位置开始,查找字符c,返回找到的位置索引,-1表示查找不到字符;
- size_t rfind (constchar* s, size_t pos = npos) const:在当前字符串的pos索引位置开始,反向查找子串s,返回找到的位置索引,-1表示查找不到子串;
- size_t rfind (charc, size_t pos = npos) const:在当前字符串的pos索引位置开始,反向查找字符c,返回找到的位置索引,-1表示查找不到字符;
- size_t find_first_of (const char* s, size_t pos = 0) const:在当前字符串的pos索引位置开始,查找子串s的字符,返回找到的位置索引,-1表示查找不到字符;
- size_t find_first_not_of (const char* s, size_t pos = 0) const:在当前字符串的pos索引位置开始,查找第一个不位于子串s的字符,返回找到的位置索引,-1表示查找不到字符;
- size_t find_last_of(const char* s, size_t pos = npos) const:在当前字符串的pos索引位置开始,查找最后一个位于子串s的字符,返回找到的位置索引,-1表示查找不到字符;
- size_t find_last_not_of (const char* s, size_t pos = npos) const:在当前字符串的pos索引位置开始,查找最后一个不位于子串s的字符,返回找到的位置索引,-1表示查找不到子串;
- strtok()
- void test()
- {
- char str[] = "I am a student; hello world!";
-
- const char *split = ",; !";
- char *p2 = strtok(str,split);
- while( p2 != NULL )
- {
- cout<<p2<<endl;
- p2 = strtok(NULL,split);
- }
- }
参考下面的链接