使用C语言编写的应用程序经常使用strcpy 等字符串复制函数、strcat等拼接函数,还经常使用strlen来确定字符串的长度;具有较强C语言背景的C++程序员编写的应用程序亦如此。这些C风格字符串作为输入的函数非常危险,因为它们会寻找终止空字符,如果程序员没有在字符数组末尾添加空字符,这些函数将跨越字符数组的边界。
C++提供了 std::string,这是一种功能强大而安全的字符串操作方式。不同于字符数组(C风格字符串实现),std::string是动态的,在需要存储更多数据时其容量将增大。
可以互相转换:
#include <iostream>
#include <string>
using namespace std;
int main()
{
char *cp="hello";
char c_arr[]="hello";
char c_arr2[]={'h','e','l','l','o'};
// c-string --> string
string s1(cp);//复制cp中的所有字符到s1中(除了末尾空字符'\0')
string s2(c_arr,2);//复制c_arr两个字符到s2中
string s3(c_arr2);//error,一直拷贝直到遇到'\0'
// string --> c-string
string str("hello");
const char *cp=str.c_str();
}
需注意C++中string赋值越界的问题,给定内存后,大小(size)就固定了,要改变要用“+=”,或者“=”,使用[index]时,index范围必须在[0,size-1]。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string temp;
temp[0]='a';//越界赋值
temp[1]='b';//越界赋值
temp[2]='c';//越界赋值
temp[3]='\0';//越界赋值
cout<<temp[0]<<temp[1]<<temp[2]<<endl;
cout<<&temp[0]<<" "<<&temp[1]<<" "<<&temp[2]<<" "<<endl;
printf("%d %d %d %d\n",&temp,&temp[0],&temp[1],&temp[2]);
cout <<temp.size()<<endl;//0,没有动态分配内存
cout<<temp<<endl;//空
cout<<"****";
string str1 = "hello";//拷贝初始化(和c-string不同)
string str2("world");
str1[0] = 'H';
str2[0] = 'W';
cout<<str1<<endl;
cout<<str2<<endl;
char *c_str = "Hello";
*c_str = 'h';//错误,因为Hello仍然在常量区,没有在堆区产生副本
}