用c连接字符串还是比较麻烦的。因为string并非c的内置类型。我们看看麻烦的情况。以连接字符串为例:
c的代码是这样的:
char * strcat_cstyle()
{
// c++ style
char* a ="hello ";
char* b ="world by c";
int len = strlen(a)+strlen(b)+1;
char*c =(char*)malloc(len);
memset(c,0,len);
strcat(c,a);
strcat(c,b);
return c;
}
你需要
- 自己计算新字符串的长度
- 自己分配并转型
- 自己清空内存区
- 然后连接
- 别忘了,用完后记得free
不这样会如何?你可以试试吧len改小,看看c遇到这样的问题的反应会如何暴烈。
还好,在c++内虽然没有string类型,但是在库内提供了一个string的类,于是:
string strcat_cppstyle()
{
// c++ style
string a ="hello";
string b ="world by c++";
return a+b ;
}
这样就很简单直接了。

被折叠的 条评论
为什么被折叠?



