注:编译平台为VC6.0
字符串类型
有C风格和标准C++库提供的string类型
标准库中使用string类
首先要#include "string"
声明方法
string foo = "Some Words Here"; //string要小写
string foo("Some Words Here"); //两种没有区别
第一种方法的好处在于我们可以用+来连接两个串了。
例如:
#include <iostream>
#include "string"
using namespace std;
int main(void){
string foo1 = "first word\t"; // \t为了连接以后的清晰
string foo2 = "second word";
string foo = foo1 + foo2;
cout<<foo<<endl;
return 0;
}
两种格式的转换 --C风格的串和string的转换
sting->C style:
#include <iostream>
#include "string"
using namespace std;
int main(void){
string len = "hello the world!";
const char * st = len.c_str(); //注意!这里要用const,c_str()返回const char *
cout<<st<<endl;
return 0;
}
C style ->string:
#include <iostream>
#include "string"
using namespace std;
int main(void){
char *len = "hello the world!"; //这里没有必要使用const
string st = len;
cout<<st<<endl;
return 0;
}
如果使用C风格的字符串,除非特殊情况,使用const比较安全。