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

  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容器区别,例:

  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. }  

错误示例:

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

相关内容