我是一个正在学习C++的同学,把自己的学习笔记和一些自己的理解记录下来。如果有什么地方写得不对,还希望各位朋友指正。我写的是有c语言基础之后学习C++ 的学习经历。并不是零基础学习C++。
5.字符串
c语言里面是没有字符串变量的,是通过字符数组来表示的。而且c语言里面的字符串有两大标识。1,字符串首地址 2,结束标志‘\0’。这里我们称它为c风格字符串。首先我们回忆一波C风格字符串有些什么处理。有获取某一个字符,赋值,比较,连接,计算长度等等操作吧。同样C++里面字符串同样也有的。当然操作起来是简单很多的。首先C++字符串的使用要包含头文件string。注意不是string.h。
下面就对比着C语言里面字符串的处理来写C++的字符串处理。
-
(1)字符串的定义。
C语言:
char a[20]=“hello,world”;
char *a=“hello,world”;
C++:实为创建string对象
string a=“hello,world”;
string b(“hello,world”);
string c(b);
这里注意一下,C风格的字符串如果声明的时候没有初始化,后面要给字符数组赋值必须要strcpy函数。但是C++不用。可以声明和初始化分开。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string a = "hello,world";//创建string对象
string b("hello,world");//创建string对象
string c;//创建string对象
c="hello,baby";
cout<<s1<<endl;
cout<<s2<<endl;
cout<<s3<<endl;
}
- (2)string对象可以转换为C风格字符串
在有的时候我们需要用到格式化输出,比如说sprintf。这个时候必须使用C风格的字符串,所以得把string转换为C风格的字符串。这里我们调用string的成员函数 c_str() 就可以做到。
#include <iostream>
#include <string>
#include <cstdio>
using namespace std;
int main()
{
string s1 = "hello world";
char buf[100];
sprintf(buf, "s1 = %s", s1.c_str());
cout<<buf<<endl;
}
- (3)字符串复制,比较,连接
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s1="hello,world";
string s2="hello,worle";
string s3="hello,baby";
s3=s2;//复制,C风格strcpy函数功能
s3+=s2;//连接,C风格strcat函数功能。注意只能string连接string。
//如果要连接不同数据类型,得用sprintf。
if(s2>s1)//比较,strcmp函数功能。直接用比较运算符进行比较。
{
cout<<s2<<endl;
}
}
- (4)获取字符串大小
成员函数s.empty()判断是否为空。
成员函数s.size()获取字符串长度(同strlen)。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = " ";
cout<<s.empty()<<endl;//0 不为空
string s2 = "";
cout<<s2.empty()<<endl;//1 为空
string s3 = "hello world";
cout<<s3.size()<<endl;
}
- (5)其他注意事项
1.如果用cin输入字符串时,不能输入空格。如果要输入空格得用getline(cin,s);
2.获取字符串某个元素同C风格字符串一样。
sring s=“hello,world”;s[i]获取字符元素
6.bool类型
C++比C语言多一个基本数据类型bool类型。bool类型只有两个值true和false,表示真假。大小为一个字节。
#include<iostream>
using namespace std;
int main()
{
bool gender=ture;
cout<<gender? boy:girl<<endl;//表示真假
cout<<boolalpha<<gender<<endl;//加一个boolalpha
//后面的bool类型数据才会以字符true或者false输出否则输出1或者0
}