学习数组(一)

本文深入探讨了C++编程中字符串处理的关键技巧,并通过实例展示了如何正确处理包含空字符的字符串,同时提供了避免此类问题的实用方法。此外,文章还介绍了字符串长度的计算、初始化和读取过程,以及如何使用`strlen()`和`sizeof()`函数进行高效操作。
</pre><pre class="cpp" name="code">#include<iostream>
int main()
{
	using namespace std;
	char dog[7]={'b','e','c','a','u',' ','2'};
	cout<<dog;
	//测试是否能输出中间还有空字符的字符串
	cin.get();
	return 0;
}

//Tips:可以用以下的代码避免以上情况
#include<iostream>
int main()
{
	using namespace std;
	char bird[7]="Mr. Cheeps";
	cout<<bird;
	//测试是否能输出中间还有空字符的字符串
	cin.get();
	return 0;
}

//Tips:strlen()为字符串长度 sizeof(name1)为数组的实际长度;字符数组会被\0截取
#include<iostream>
#include<cstring>
int main()
{
	using namespace std;
	const int Size=15;
	char name1 [Size];
	char name2 [Size]="C++owboy";
	cout<<"Howdy! I'm"<<name2;
	cout<<"! What's your name?\n";
	cin>>name1;
	cout<<"Well, "<<name1<<",your name has";
	cout<<strlen(name1)<<" letters and is stored\n";
	cout<<"in an array of "<<sizeof(name1)<<" bytes\n";
	cout<<"your initial is "<<name1[0]<<".\n";
	name2[3]='\0';
	cout<<"Here are the first 3 characters of my name : ";
	cout<<name2<<endl;
	cin.get();
	return 0;
}


 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值