C++ 学习之路(五)
一、string 类型的函数
1. c_str()
c_str() 是c++ 字符串类型的函数,其返回当前字符串首字符的地址,主要以const char* 形式得到string内容。通常与strcpy服用效果更佳。直接上代码:
#include <iostream>
#include <cstring>
using namespace std;
int main() {
string ChineseName = "xiaohong";
string EnglishName = "Jerry";
// define dynamic allocation memory
char* DAM = new char[ChineseName.length() + EnglishName.length() +1];
// copy ChineseName to DAM
strcpy(DAM,ChineseName.c_str());
// add new sting to DAM
strcat(DAM," ");
strcat(DAM,EnglishName.c_str());
// xiaohong Jerry
cout << DAM << endl;
return 0;
}
注意c_str() 输出的是 const char*,返回的是字符串首字符的地址, 如下所示:
#include <iostream>
#include <cstring>
using namespace std;
int main() {
string name = "wangxiaohong";
const char* first = name.c_str();
char a[20];
strcpy(a,name.c_str());
// w wangxiaohong 12 wangxiaohong
cout << *first << "\t" << first << '\t' << strlen(first) << "\t" << a << endl;
return 0;
}
从中可以看出 name.c_str() 返回的是name 的首字符,而其长度是12, 通过strcpy也可以得到完整的字符串。
c_str() 也可以转化成其他形式,如整形和浮点型(atoi, atof) 如下所示:
#include <iostream>
#include <cstring>
using namespace std;
int main() {
string level = "level 1.10";
// output the number in float
int sInd = 0, eInd = 0;
sInd = level.find(' ',sInd) +1;
eInd = level.find(' ',sInd);
string cstr = level.substr(sInd,eInd-sInd);
float cfloat = atof(cstr.c_str());
//1.10
cout << cstr << endl;
// 1.1
cout << cfloat<< endl;
return 0;
}
可以看出,如果将cstr.c_str() 用别的形式表达出来,其返回的是cstr用其他形式表达出来的值。