C++中的string类

C++中的string类
1)是什么:
专门的字符串操作的一个类,非常强大,字符串CString,QString
2)跟char *的区别
Char *是指向字符数组首地址的指针,然后我们系统提供一个string.h,这个头文件声明了很所字符串操作函数,strlen、strcat、strcmp、strcpy…….
Stirng这个类,我们使用的时候不用考虑内存非配与释放,不用担心越界,因为前辈在封装string的时候,已经把几乎所有的情况都考虑到了,
3)学习方法,学会查找三种方式:MSDN、工具书、百度
4)头文件 #include<string>
且一定要加using namespace std
String的构造函数
1)String str;
2)string str(5,’a’);给str初始化为5个a
3)string str(“awefgweg”);
str.empty()==0,表明字符串为空
4) string str("aewgwea",4);给字符串str赋值为aewg
5)string str(“abcdefgh”,2,4);给字符串str赋值为cdef,4表示长

6)string str1(str); 拷贝构造
String类成员函数
1)Str.size(); 求str子符个数
2)str.capaciyt() 求str容量,一个空的str,他的容量为15,为了提高效率,当超过15时,此时容量15+16;当超过31时,15+16+16,……..以此类推,每次超出都会新增加16.
3)str.capacity(size_t);改变str的大小,会当超出处理,每次增加16
4) str.length();求字符串长度,大小和(1)相同。
5) str.resize(3);截取字符串
6)cout << str[3] << endl; 输出字符串str中的第三个字符。

增删查改

1)增

插入字符串

insert() 函数可以在 string 字符串中指定的位置插入另一个字符串,它的一种原型为:

string& insert (size_t pos, const string& str);

pos 表示要插入的位置,也就是下标;str 表示要插入的字符串,它可以是 string 变量,也可以是C风格的字符串。

  1.  
  2.     int main(){
  3.     string s1, s2, s3;
  4.     s1 = s2 = "1234567890";
  5.     s3 = "aaa";
  6.     s1.insert(5, s3);
  7.     cout<< s1 <<endl;
  8.     s2.insert(5, "bbb");
  9.     cout<< s2 <<endl;
  10. return 0;

运行结果:
12345aaa67890
12345bbb67890

注意:insert有可能会越界。

2)

string& erase (size_t pos = 0, size_t len = npos);

pos 表示要删除的子字符串的起始下标,len 表示要删除子字符串的长度。如果不指明 len 的话,那么直接删除从 pos 到字符串结束处的所有字符(此时 len = str.length - pos)。

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4.  
  5. int main(){
  6.     string s1, s2, s3;
  7.     s1 = s2 = s3 = "1234567890";
  8.     s2.erase(5);
  9.     s3.erase(5, 3);
  10. cout<< s1 <<endl;
  11. cout<< s2 <<endl;
  12. cout<< s3 <<endl;
  13. return 0;

运行结果:
1234567890
12345
1234590
有读者担心,在 pos 参数没有越界的情况下, len 参数也可能会导致要删除的子字符串越界。但实际上这种情况不会发生,erase() 函数会从以下两个值中取出最小的一个作为待删除子字符串的长度:

  • len 的值;
  • 字符串长度减去 pos 的值。
    说得简单一些,待删除字符串最多只能删除到字符串结尾。

3)提取字符串

string substr (size_t pos = 0, size_t len = npos) const;

pos 为要提取的子字符串的起始下标,len 为要提取的子字符串的长度。

  1. int main(){
  2.     string s1 = "first second third";
  3.     string s2;
  4.     s2 = s1.substr(6, 6);
  5.     cout<< s1 <<endl;
  6.     cout<< s2 <<endl;
  7.     return 0;
  8. }

运行结果:
first second third
second

 

posted @ 2017-09-15 08:24  zwj鹿港小镇  阅读(176)  评论(0编辑  收藏  举报