C/C++ strlen()与sizeof()及数组中使用字符串

20 篇文章 0 订阅
16 篇文章 0 订阅

strlen()与sizeof()

注意

  • strlen()使用了**标准c语言库函数strlen()**来确定字符串长度头文件加入#include<cstring>
  • sizeof运算符指出整个数组的长度15字节,strlen()只计算可见的字符返回储存再数组中的字符串的长度
#include<iostream>
#include<cstring>
using namespace std;
int main(void)
{
	const int size=15;
	char name1[size];
	char name2[size]="C++owboy";
	cin>>name1;
	cout<<name1<<endl;
	cout<<"Well "<<name1<<" you name has ";
	cout<<strlen(name1)<<" letters and is stored";
	cout<<" in an array of is "<<sizeof(name1)<<" bytes\n";
	name2[3]='\0'; //运送一个空字符过去
	cout<<"Here are the first charcaters of my name: "<<name2<<endl; 
} 

程序运行结果

penglu
penglu
Well penglu you name has 6 letters and is stored in an array of is 15 bytes
Here are the first charcaters of my name: C++

程序说明

  • 对于char数组类型字符串,如果cosmic是字符串,则数组的长度不得短语strlen(cosmic)+1
  • c-风格字符串以‘\0’结尾,对于cout显示上述字符串,直到遇到空字符‘\0’停止
  • 因此将name[3]设置为空字符,该字符串在第3个字符后即结束即使数组还有其他字符
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值