关于 c++ 字符和字符串

 字符串(string str)

            求长度     str.length()

 数组

     字符型 (char ch[ ])

             求长度    strlen(ch) 

      整形 (int N[ ])

               求长度   sizeof(N)/4                    



字符串(双引号)

 实际上是使用 null 字符 \0 终止的一维字符数组

/ srtring字符串

头文件 #include<string>

string str;//创建空字符串

cin是以空格或回车结束的 , 用它输入 , 字符串不会存在空格或换行符

字符串长度

         size   length  不做区别

string str ="asdzxc";
cout << size(str) << endl;      //6
cout << str.length() << endl;   //6

输出

string str = "asdzxc";
cout << str << endl;

>>asdzxc

数组(长度是确定的)

  字符数组(单引号)

  此六行表示的意义相同 , 数组下标从0开始 , 末尾必须要留'\0'的位置

char arr[6] = { 'a','s','d','z','x','c' };
char arr[6] = { 'a','s','d','z','x','c' ,'\0'};
char arr[] = { 'a','s','d','z','x','c' };
char arr[] = "asdzxc";
char arr[] = {"asdzxc"};
char arr[6] = "asdzxc";

字符型数组长度

strlen  -----数组有效长度(不包括"\0")

sizeof   ---- 数组长度(内存大小 / 数据类型所占内存 )

sizeof表示所占内存的大小,char类型占一个字节 , '\0'也占一个字节

	char arr[] = "asdzxc";

	cout << strlen(arr) << endl;   //  >>6

	cout << sizeof(arr) << endl;   //  >>7

输出

不需要遍历,直接输出

char ch[] = "China";
cout << ch << endl;

>>China

整形数组(不带任何)

末尾没有'\0'的位置 , 需要遍历输出

int N[5] = { 1,3,4 };
for (int i = 0; i < 5; i++)
{
	cout << N[i];
}
cout << endl;
return 0;

>>13400

数组所占字节

sizeof

int N[] = { 1,3,4 };
cout << sizeof(N) << endl;

>>12

数组长度

int 数据类型占四个字节

int N[] = { 1,3,4 };
for (int i = 0; i < sizeof(N)/4; i++)
{
	cout << N[i];
}
cout << endl;

>>134

输入空格

  用cin输入的字符串 / 字符数组 中有空格 , 直接结束

char ch[3];
cin >> ch ;
cout << ch << endl;

 / 使用 getline(cin,str)

string str;
getline(cin,str);
cout << str << endl;

 / 使用cin.getline(ch ,需要输入的字符个数,结束标志)

 cin.getline(str,8,'m'),当输入abcdefghijklmn时,输出abcdefg,因为第8位是不可见字符'\0'
 cin.getline(str,8,'e'),当输入abcdefghijklmn时,输出abcd

此函数会一次读取多个字符(包括空白字符)。它以指定的地址为存放第一个读取的字符的位置,依次向后存放读取的字符,直到读满N-1个,或者遇到指定的结束符为止。若不指定结束符,则默认结束符为'\n'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值