1 长度
要想得到数组长度有4种操作sizeof(a)、strlen(a)、size()、length()
通过下面一段代码可以大概了解它们之间的差别
#include<iostream>
#include<string> //size()和length()使用
#include"string.h" //strlen()使用
using namespace std;
int main()
{
int a[10] = {1,2};
char * b = NULL;
string c = "123";
char d[10] = {'g','4','\0','g'};
int num1 = sizeof(a); //a所占空间的大小
cout << "sizeof(a)的大小为: " << num1 << endl;
num1 = sizeof(a)/sizeof(int); //a中元素的个数
cout << "sizeof(a)/sizeof(int)的大小为: " << num1 << endl;
num1 = sizeof(b); //字符指针所占空间的大小
cout << "sizeof(b)的大小为: " << num1 << endl;
num1 = strlen(d);//从第一个到‘\0’(不包括)之间元素的个数
cout << "strlen(d)的大小为: " << num1 << endl;
num1 = sizeof(d);//d所占字节的大小 (char类型占1个字节)
cout << "sizeof(d)的大小为: " << num1 << endl;
num1 = strlen(c.c_str());//strlen(k)后面的参数类型必须是char* ,char a[],string类型(用c_str()转换成char*)
cout << "strlen(c.c_str())的大小为: " << num1 << endl;
num1 = c.size(); //string专属
cout << "c.size()的大小为: " << num1 << endl;
num1 = c.length();//string专属
cout << "c.length()的大小为: " << num1 << endl;
return 0;
}
size(),length() ,是string的专属,统计字符个数
strlen(a),用来统计字符数组里到‘\0’为止的字符个数,a只能是char*,char a[],或者由string通过c_str()转化的类型
sizeof(a),用来统计a所占空间的字节大小,a为任意类型都可以
2 类型转换
还是先看一段代码
#include<iostream>
#include<string> //copy data c_str头文件
#include"stdlib.h" //atoi头文件
#include <sstream> //stringstream头文件
using namespace std;
int main()
{
string a = "123li";
char* b = NULL;
int num = a.size();
char c[num] = {'0'};
b = (char*)a.c_str(); //c_str()转换成const char*类型,所以要转换成char*需要强制转换
cout << "b = (char*)a.c_str()为: ";
for(int i = 0; i < num; i ++)
cout << *(b++);
cout << endl;
const char* d = a.data();
cout << "d = a.data()为: ";
for(int i = 0; i < num; i ++)
cout << *(d+i);
cout << endl;
a.copy(c,num,0); //第一个参数char*类型(char[]也行),第二参数拷贝个数,第三参数起始位置
cout << "a.copy(c,num,0)为: ";
for(int i = 0; i < num; i ++)
cout << c[i];
cout << endl;
char* p = "hello";
a = p;
cout << "char* 转 string 为:" << a << endl;
a = "123li";
int out = atoi(a.c_str()); //开始是数字到第一个非数字止,要是开始是数字直接返回0
cout << "out = atoi(a.c_str())为:" << out << endl;
//itoa(out,a,10); //编译错误
stringstream ss; //数字和字符串互转
double dou = 0.12542;
ss << a;
ss >> dou;
cout << "stringstream转换为: " << dou << endl;
return 0;
}
string 转 char*有data()、copy()、c_str()
转char[]有copy()或者循环赋值
char*转string直接赋值
char转int有atoi()、stringstream
数据类型转char有stringstream