一、string概述
string是一个字符串的类,它集成的操作函数足以完成大多数情况下的需要。我们甚至可以把它当作C++的基本数据类型。
头文件:#include <string>
注意:string.h和cstring都不是string类的头文件。这两个头文件主要定义C风格字符串操作的一些方法,如strcpy() 、strlen()等。string.h是C语言头文件格式,而cstring是C++头文件格式,但是它和string.h是一样的,它的目的是为了和C语言兼容。
二、C++字符串和C字符串的转换
C++提供的由C++字符串转换成对应的C字符串的方法:data() 、c_str() 、copy()。需要注意的是,C++字符串并不以'\0'结尾。
1、data()
data() 是以字符数组的形式返回字符串的内容,但是并不添加'\0'。
2、 c_str()
c_str()返回一个以'\0'结尾的字符数组。c_str() 语句可以生成一个const char*指针,并且指向空字符的数组。这个数组的数据是临时的,当有一个改变这些数据的成员函数被调用后,其中数据就会失效。故要么现用现转换,要么把它的数据复制到用户自己可以管理的内存中后在转换。
string str = "Hello, I am LiMing.";
const char* cstr = str.c_str();
cout << cstr << endl;
str = "Hello, I am Jenny";
cout << cstr << endl;
改变了str的内容,cstr的内容也随之改变,可以考虑把数据复制出来解决问题。
char *cstr = new char[20];
string str = "Hello, I am LiMing.";
strncpy(cstr, str.c_str(), str.size());
cout << cstr << endl;
str = "Hello, I am Jenny";
cout << cstr << endl;
使用strncpy函数将内容进行复制,这样可以保证cstr中的内容不会随着str的改变而改变。
3、 copy()
copy()是把字符串的内容复制到或写入既有的c_string或者字符数组中。
copy(p, n, size_type _Off = 0):表明从string类型对象中至多复制n个字符到字符指针p指向的空间中,并且默认从首字母字符开始,也可以指定开始的位置(从0开始计数),返回真正从对象中复制的字符。不过用户要确保p指向的空间足够来保存n个字符。
size_t length;
char buf[8];
string str("Hello, I am LiMing.");
cout << str << endl;
length = str.copy(buf, 7, 3);
cout << "length:" << length << endl;
buf[length] = '\0';
cout << "str.copy(buf, 7, 5), buf contains:" << buf << endl;
cout << "buf len :" << strlen(buf) << endl;
length = str.copy(buf, str.size(), 3);
cout << "length:" << length << endl;
buf[length] = '\0';
cout << "str.copy(buf, str.size(), 5), buf contains:" << buf << endl;
cout << "buf len :" << strlen(buf) << endl;
三、string和int的转换
1、使用sstream
//int 转 string
int a_1 = 99;
string str_1;
stringstream ss;
ss << a_1;
ss >> str_1;
cout << "a_1:" << a_1 << endl;
cout << "str_1:" << str_1 << endl;
//string 转 int
int a_2;
string str_2 = "12345";
ss.clear();//清除ss中的数据
ss << str_2;
ss >> a_2;
cout << "str_2:" << str_2 << endl;
cout << "a_2:" << a_2 << endl;
2、使用既有的函数
//string 转 int
string str_3 = "54321";
int a_3 = stoi(str_3);
cout << "str_3:" << str_3 << endl;
cout << "a_3:" << a_3 << endl;
//int 转 string
int a_4 = 54321;
string str_4 = to_string(a_4);
cout << "a_4:" << a_4 << endl;
cout << "str_3:" << str_3 << endl;
四、其他函数
int capacity() const; //返回当前容量,即string中不必增加内存即可存放的元素的个数
int max_size() const; //返回string对象中可存放的最大字符串长度
int size() const; //返回当前字符串大小
int length() const; //返回当前字符串长度
bool empty() const; //当前字符串是否为空
void resize(int len, char c); //把当前字符串大小置为len,并用字符c填充不足的部分。