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

来源:互联网 发布:linux 程序运行权限 编辑:程序博客网 时间:2024/04/30 15:26
概念区分

在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类,示例:

[cpp] view plaincopyprint?
  1. #include<iostream>  
  2. #include<string>  
  3. using std::string;  
  4. using namespace std;  
  5. int main(){   
  6. string s = "abcdefg";  
  7. string::iterator i;//支持迭代器   
  8. for(i=s.begin();i!=s.end();i++)  
  9.   cout<<*i<<" ";//逐个输出string s中的元素   
  10.  system("pause");  
  11.  return 0;  
  12. }  

与vector容器区别,例:

[cpp] view plaincopyprint?
  1. #include<iostream>  
  2. #include<vector>  
  3. using namespace std;  
  4. int main()  
  5. {  
  6. vector<string> s(5,"abcdefg");  
  7. vector<string >::iterator i;  
  8. for(i=s.begin();i!=s.end();i++)  
  9.   cout<<*i<<" ";//逐个输出vector s中的元素   
  10.  system("pause");  
  11.  return 0;  
  12. }  


c中的字符串

错误示例:

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)。

静态内存分配示例:

[cpp] view plaincopyprint?
  1. #include<iostream>  
  2. using namespace std;  
  3. int main()  
  4. {  
  5.     char *p;  
  6.     p="hello";  
  7.     cout<<p<<endl;  
  8.     system("pause");  
  9. }  


参考:

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

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

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

char*参数构造函数和string参数构造函数

另外,不建议采用

[cpp] view plaincopyprint?
  1. char *a=  new char[20];  
  2.   
  3. a="hello world";//不建议这么用,会产生常量歧义:指针a被常量化为"hello world",就好比a=NULL。建议采用strcpy(a,"hello world");或者strcpy_s(a,"hello world");的方式  
  4.   
  5. delete []a;  
0 0
原创粉丝点击