c++中string种字符串和c中char*/char[]型型字符串的区别

c++中string类字符串和c中char*/char[]型型字符串的区别
概念区分

在c中,是没有string类型的数据的。但是c语言里有<string.h>这个头文件。容易让人误认为c中有string类型的数据。

区分string的含义:

1)(在c和c++中)如果string表示字符串型数据,那么c中是有字符串类型数据的(用char[]或者char *来声明定义)。但是没有string类型数据。而c中的<string.h>这个头文件里声明的函数原型也全是针对char数组的种种操作,如strcmp,strcpy,strcat等。

2)(在c++中)如果string表示string类型,那么c++中才有,c中没有。string在c++中是一种特殊的类。string 和 vector、list一样,都是标准库类型。 string 类型支持长度可变的字符串,C++ 标准库将负责管理与存储字符相关的内存,以及提供各种有用的操作。

需要:

#include <string>
using std::string;

c++中string类,示例:

#include<iostream>
#include<string>
using std::string;
using namespace std;
int main(){ 
string s = "abcdefg";
string::iterator i;//支持迭代器 
for(i=s.begin();i!=s.end();i++)
  cout<<*i<<" ";//逐个输出string s中的元素 
 system("pause");
 return 0;
}
c++中string种字符串和c中char*/char[]型型字符串的区别

与vector容器区别,例:

#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<string> s(5,"abcdefg");
vector<string >::iterator i;
for(i=s.begin();i!=s.end();i++)
  cout<<*i<<" ";//逐个输出vector s中的元素 
 system("pause");
 return 0;
}
c++中string种字符串和c中char*/char[]型型字符串的区别

c中,参考:

基础备忘:new\delete和malloc\free及memset

字符串指针与char型指针数组

基础备忘:字符数组、字符串和字符串处理基本函数

错误示例:

int main(int argc, char* argv[])
{
char *n;
n=new char[20];
n="Hello World";
printf("%s\n",n);
return 0;
}
上述代码有误,指出其中三个错误:
第一,C语言里没有new。
C中是这样的:
char * n;
n = (char *)malloc(sizeof(char) * 20);
第二,分配的空间在栈中,不能给它直接等堆里的常量。
n = "Hello, World!"; // 错
应该是 strcpy(n, "Hello, World!");
第三,C/C++中分配了空间要释放。
C++中new了就要delete,其中 new [] 和 delete []配对,new 和 delete 配对。
C中用malloc分配的内存对应的是 free。
所以上述代码中需要要 free (n)。