1 字符串string与字符数组char[ ]的异同
1.1 了解字符char与字符串的区别
- a char类型不是C++的基本数据类型,实质上是8位的整数类型,在计算机保存的是它的AS II码,而不是字符本身,使用时
系统再将其转换过来;
- b 掌握基本的一些转义符;
- c 字符串是字符组成的串(非集合,可重复)。
- d 字符用单引号标注,字符串用双引号标注
- e 字符是一个元素,且只能存放单个字符,而字符串可以存放多个,并以'\0'结束('\0',空,串的结束符,一个转义符);
1.2
字符串string与字符数组char[ ]的区别
- 都是字符的集合,但是字符数组不需要以'\0'结束;
- string的使用需要头文件string,即#include<string>
- 在头文件string.h 中,有关于string对象的一些操作(对象的一些操作方式),比字符数组操作更为方便
- string的size操作结果的变量是string::size_type类型(非int 类型,是int类型的能够存储的长度的两倍)
- 从字符串string对象中获取字符的操作与char[ ]的操作一样
代码示例
#include<iostream>
#include<string>
using namespace std;
//using std::string;
int main() {
char char1='a';
cout<<char1<<" size "<<sizeof( char1)<<endl;
string s1; //定义
string s2("Hello world!");
string s3 = "We are happy!\0"; //不会显示\0
//string s4 = (4,'c');
string s5= "We are happy!";
cout<<"The size of s1 is "<<s1.size()<<endl;
cout<<s2<<'\n'<<s3<<endl;
cout<<s3<<' '<<s3.size()<<'\n'<<s5<<' '<<s5.size()<<endl;
///char[] char_str1; //有误
char char_str2[11]; //定义中必须要指明存储大小
for ( int i = 0; i <= 10; i++ ) {
char_str2[i]=s2[i];
}//通过循环给字符数组初始化
cout<<"The size of "<<char_str2 <<" is " << sizeof(char_str2)<<endl;
//有误
char char_str3[] = "hello world";
char char_str4[] = "I am so full!\0";
string s6(char_str3); //通过字符数组给字符串赋值
//s6=s6(char_str3); //行不通
cout<<s6<<" is "<<s6.size()<<endl;
//char_str4 = s3; //将字符串赋值给字符数组
cout<<char_str4<<" is "<<sizeof(char_str4)<<endl;
//通过输入流给字符串赋值,遇到空格结束
cin>>s1;
cout<<s1<<endl;
return 0;
}
运行结果:
2 字符指针可以多次赋值
char * char_str1[ ];
char_str=" we are so happy and so disappionted!";
cout<<char_str<<endl;
char_str=char_str2;
cout<<char_str<<endl;