P33_字符串的基本操作

#include <iostream>
#include <string>
using namespace std;

//字符串
//1 C语言的字符串  以零结尾的字符串
//2 在C语言中没有字符串类型  通过字符数组  来模拟字符串
//3 字符串的内存分配  堆上  栈上  全局区(很重要)
void main51()
{
	//1 指定长度
	char buf2[100] = {'a','b','c','d'};

	//2 不指定长度  C编译器会自动帮助程序员  求元素的个数
	char buf1[] = {'a','b','c','d'};  //   buf1是一个数组  不是一个以0结尾的字符串

	cout << buf1 << endl;
	cout << buf2 << endl;
}

//用字符串  来  初始化字符数组
//strlen()  长度  不包括0
//sizeof()  内存块的大小
int main52()
{
	char buf3[] = "abcd";  // buf3 作为字符串  应该是5个字节  //作为字符串  应该4个字符串
	char buf4[111] = "shoieoiheoijfoewjfoiewf";

	int len = strlen(buf3);

	int size = sizeof(buf3);

	cout <<"buf3字符的长度:"<<len << endl;

	cout << "buf3数组所占内存空间大小"<<size << endl;

	//buf3 作为数组  数组是一种数据类型  本质(固定大小内存块的别名)
	cout << buf4 << endl;


	return 0;
}

//通过数组下标 和  指针
int main()
{
	int i = 0;
	char buf5[128] = "abcdefg";//buf

	for (i = 0; i < strlen(buf5); i++)
	{
		cout << buf5[i] << endl;
	}

	char *p = NULL;
	p = buf5;
	for (i = 0; i < strlen(buf5); i++)
	{
		cout << *(p+i)<<endl;
	}


	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_41983807/article/details/87902883
今日推荐