一、求数组长度——使用sizeof()函数
int arr[] = {1,3,5,2,6,8,2,3,15};
cout << "lenth of arr = " <<sizeof(arr) / sizeof(arr[0]) << endl;
//注:这种方法无需引入额外的头文件
二、求字符串长度(注意,size()和length()是用来求字符串长度的,用于普通数组则会报错,用于char[]字符数组也会报错)
1、sizeof()函数:除了基本用法,还应关注string与char[]的区别
char cha[] = "hello";
string str = "hello";
cout << "lenth = " <<sizeof(cha)<< endl; // 结果是6,因为有一个结尾符
cout << "lenth = " <<sizeof(cha) / sizeof(cha[0]) << endl; // 结果是6,同理
cout << "lenth = " <<sizeof(str)<< endl; // 结果是32,这里相当于在看str指针本身的内存大小
cout << "lenth = " <<sizeof(str[0])<< endl; // 结果是1
//此时仍无需添加额外的头文件(确切地说,无需 #include <String> )
2、size()与length()运算符:
1)size() 与 length() 用法几乎完全一致,且不需要引入<String>头文件(纠正长久以来的错觉)
2)size()除了可以获取string类型的长度,也可以用来获取vector类型的长度
3)不能用于获取普通数组(如int arr[])的长度,也不能用于获取字符数组长度(如char cha[])
4)size()和length()运算符返回的长度为字符串的净长度,即不把字符串结尾符算在内(使用sizeof(字符串或字符数组)/sizeof(代表元)得到的是真实长度,考虑了结尾符,要区别开!)
char cha[] = "hello";
string str = "hello";
cout << "lenth_str = " <<str.length() << endl; //结果是5,length()算符不会把字符结尾符算进去
cout << "lenth_cha = " <<cha.length() << endl; //错误写法!
cout << "lenth_str = " <<str.size() << endl; //结果是5,length()算符不会把字符结尾符算进去
cout << "lenth_cha = " <<cha.size() << endl; //错误写法!
//此时仍无需添加额外的头文件(确切地说,无需 #include <String> )