本文共 1784 字,大约阅读时间需要 5 分钟。
一:变量初始化新方式
(1)int a = 10;//传统的变量初始化方式
(2)c++新标准支持的初始化方式
int b{ 2 };int c = { 4 };int d(3);int e = (5);
那么使用()和{}对变量进行初始化是否有好处?
答案是肯定的。在传统的变量初始化方式中,
int a = 10.6f;//可以把一个浮点型数据赋给一个整型变量,编译器只会提示,丢失精度
然而,这样赋值,编译器直接会报错。
int a{ 2.5f };int b={ 2.5f };int g(3.1f);int h = (5.5f);
这种新的赋值方式,进一步保证了书写的代码的健壮性。
二:string类型
(1)string:用来处理可变长字符串用的,string类型位于using namespace std命名空间中, 使用时需要包含#include 头文件,string类型可以理解成一个类类型。(2)string类型的初始化方式
string s1 ;//空串,内容为""; string s2 = "I LOVE CHINA";string s3("I LOVE CHINA");string s4 = s3;string s5 = { "dadad" };string s6 { "dadad" };string s7 (5, 'a');//"aaaaa"string s8 { 3, 'a' };//"aaa"
(2)string常用的操作
(a)判断是否为空,empty(),返回布尔值。
string s1 ;if (s1.empty()) //成立{ cout<<"s1为空"<
(b)size()/length(),返回字节数/字符数量。返回一个无符号数。
string s1 ;cout << s1.size() << endl; //0cout << s1.length() << endl; //0string s2 = "abc";cout << s2.size() << endl; //3cout << s2.length() << endl; //3string s3 = "我爱你";cout << s3.size() << endl; //6,一个汉字两个字符cout << s3.length() << endl; //6
©s[n],返回s中的第n个字符,n的范围是0-s.size()-1,
string s1="dklajdal";cout << s1[3] << endl;//a,n从0开始
(d)字符串拼接
string s1="dklajdal";string s2 = "abc";string s3 = s1 + s2;cout << s3 << endl;//"dklajdalabc"
(e)判断字符串是否相等
string s1="dklajdal"; string s2 = "abc"; if (s1 != s2) { cout << "s1不等于s2" << endl; } string s3 = "abc"; string s4 = "abc"; if (s3 == s4)//大小写敏感,长度相等,大小写一样 { cout << "s3等于s4" << endl; }
(f)s.c_str(),返回一个字符串s中的内容指针(常量指针),出现这个的原因只要是为了与c语言当中的字符指针相兼容。
string s1="dklajdal" const char *p = s1.c_str();//p指向了s1当中的字符串了
(g)读入内容
string s1;cin >> s1;cout << s1 << endl;
(h)和字面值相加,这里涉及到了类的隐式类型转换。
string s1="ab";string s2 = "bc";string s3 = "aa" + "bb";//错误string s4 = "aa" + "bb" + s2;//错误string s5 = s1 + "bb";string s6 = "aa" + s1 + "bb";//"aa"和s1相加生成了临时的string对象
转载地址:http://vlkcz.baihongyu.com/