五、字符串(重点)
1、回顾C中的字符串
1)双引号常量字符串:“hello”
2)字符指针:char*
3)字符数组:char[]
2、C++中兼容C的字符串的同时,增加了string类型专门表示字符串
1)定义字符串
string s;//定义一个空字符串
string s = “hello”;//定义字符串同时初始化
//下面两种写法和上面写法等价
string s = string(“hello”);
string s(“hello”);
2)字符串拷贝:=
string s1 = “hello”;
string s2 = “laozhu”;
s1 = s2;//拷贝
cout << s1 << endl; //“laozhu”
3)字符串连接:+ +=
string s1 = “hello”
string s2 = " world";
string s3 = s1 + s2;
cout << s3 << endl;//hello world
s1 += s2;//s1 = s1 + s2;
cout << s1 << endl;//hello world
4)字符串比较:== 、 != 、> 、 < 、 >= 、 <=
string s1 = “hello”;
if(s1 == “hello”){//1、逻辑真
……
}
if(s1 > “laozhu”){//逻辑真
……
}
5)获取字符串中某个字符:[ ]
string s1 = “hello”;
cout << s1[0] << endl;//‘h’
s1[0] = ‘H’
cout << s1 << endl;//Hello
6)string类型中常用函数
size() 或者 length():获取字符串的长度
c_str():将string转换成C中const char*字符串
string s = “hello”;
s.size();//5
s.length();//5
const char* p = s.c_str();
eg:08string.cpp
#include <iostream>
#include <cstring>//使用了strlen函数引入的头文件
using namespace std;
int main(void){
string s = "hello";
cout << s << endl;//"hello"
//拷贝
string s2 = s;
cout << s2 << endl;//"hello"
//连接
s = s + "world";
cout << s << endl;//"hello world"
//比较
cout << (s == s2) << endl;//0
cout << (s2=="hello") << endl;//1
//获取字符串中某个字符
s[0] = 'H';
s[6] = 'W';
cout << s<< endl;//Hello World
//获取字符串的大小(长度)
cout << s.size() << endl;//11
cout << s.length() << endl;//11
cout << strlen(s.c_str()) << endl;//11
return 0;
}
练习:使用string类型,从键盘读取一个字符串,统计该字符中包含多少个字符‘a’;
提示:
string str;
cin >> str;//从键盘读取每一个字符串
string.cpp
#include <iostream>
using namespace std;
int main(void){
string str;
cout << "请输入一个字符串:" << endl;
getline(cin, str);//碰到回车结束
int count = 0;
for(int i=0; i<str.size(); i++){
if(str[i] == 'a'){
count += 1;
}
}
cout << "字符a的个数是:" << count <<endl;
return0;
}