1, 首先在使用std::string 时,需要include 哪个文件?
需要区分#include 和 #include
#include 声明的是C语言的字符串处理函数,例如strcpy, strcmp, 等等。由C语言升级到C++后需要使用#include
而#include 声明的是std::string 类。
由C语言的带.h 的头文件,对应c++的不带.h的头文件。大部分都是直接去掉.h就行了。string这个有点特殊。
2,string + 整形,拼成新的字符串。
开始我还以为可以 std::string("abdc") + 40; 字符串和整数直接运算呢。尝试后不行,应该是Java的语法。
(1) 想用 itoa(), 才发现在Linux环境下不能用,itoa是广泛使用的非标准C语言和C++语言扩展功能。因为它是一个非标准的C / C++语言功能,所以不能好好被用于所有编译器。但由于大多数编译器(如Windows)通常在< stdlib.h> | | < cstdlib >头文件包含非标准函数。
(2)换个常规做法,使用sprintf 函数
//file: StringChar.cpp
#include
#include
int main()
{
std::string name;
//字符串数组的初始化
char tmp[10] = {'\0'};
//itoa(1,tmp,10); //编译器不识别
sprintf(tmp,"%d",40);
name = "testNum " + std::string(tmp); //这里用到char *初始化字符串
printf("\n output %s . \n",name.c_str()); //这里c_str(),是string转换为char *
return 0;
}
编译:g++ StringChar.cpp -o test
运行:
Test_StringChar# g++ StringChar.cpp -o test
Test_StringChar# ./test
output testNum 40.
(3) c++ 11, 有一个简单的全局方法 std::to_string(int i);
#include
#include
int main()
{
std::string name;
//char tmp[10] = {'\0'};
//sprintf(tmp,"%d",40);
//name = "testNum " + std::string(tmp);
name = "testNum " + std::to_string(1);
printf("\n output %s.\n",name.c_str());
return 0;
}
运行结果:
Test_StringChar# g++ StringChar.cpp -o test
Test_StringChar# ./test
output testNum 1.
(4) c++ 使用输出流,将int转换为str
static std::string int2str(int i)
{
std::ostringstream out;
out << i;
return out.str();
}
3. 将字符指针赋值给string,不能为NULL
char *pStr;
std::string test = pStr;
这里有一个大坑,pStr不能为NULL。 test = pStr 会对pStr进行解引用。如果是NULL的话,会crash。
关键字:
std::string()
c_str()