STL string 类总结

来源:互联网 发布:现货指标公式源码下载 编辑:程序博客网 时间:2024/06/05 17:01

一、

最简单的字符数组可以如下定义:
   char staticName [20];//缺点是不能调整静态数组的长度 
为了避免上述缺点C++支持动态的分配内存,定义动态的字符数组如下:
   char* dynamicName = new char [ArrayLength];//为多个元素分配内存,成功后,new将返回指向一个指针,指向分配的内存。                                           delete[] dynamicName;//如果要在运行阶段改变数组的长度,必须首先释放之前分配给它的内存,再重新分配内存来存储数据。

二、最常用的字符串操作函数包括:

 复制、连接、查找字符和子字符串、截短、使用标准模板库提供的算法实现字符串的反转和大小写转换。  注意:使用STL string类,必须包含头文件 string

三、使用STL string 类

1、实例化和复制STL string:
string类提供了很多重载的构造函数,因此有很多方式进行实例化和初始化。

const char* constString = "hello world";std::string strFromConst (constString);//或std::string strFromConst = constString;

显然,实例化并初始化string对象时,无需需要关心字符串长度和内存分配的细节,该构造类会自动的完成。
2、访问std::string的字符内容

string strSTLString("hello world");cout<<strSTLString.c_str();//这里是调用的成员函数

3、拼接字符串
std::string::operator+=
std::string::append()

#include <iostream>#include <string>using namespace std;int main() {    string strSample1("Hello");    string strSample2("String");    strSample1 += strSample2;//use std::string::operator+=    cout << strSample1 << endl;    strSample1.append(strSample2);//use std::string::append()    cout << strSample1 << endl;    return 0;}

4、在string中查找字符串或字符
使用find()

string strSample("Hello String! Wake up to a beautiful day!"); strSample.erase(13, 28);//这里调用了erase()函数在给定偏移位置和字符数时删除指定数目的字符auto iCharS =find (strSample.begin(),strSample.end(),'S');if(iCharS!=strSample.end())   strSample.erase(iCharS);//在给定字符的迭代器时删除该字符strSample.erase(strSample.begin(),strSample.end());//删除迭代器范围内的函数

5、字符串反转

string strSample("Hello String! Wake up to a beautiful day!"); reverse(strSample.begin(),strSample.end());//用reverse反转字符串

6、字符串的大小写转换

std::transform
0 0