标准库类型string
使用string需要包含的头文件:
int main() {
string s1 = "Hello world ";//拷贝初始化
string s2(5, 'M');//直接初始化
string s_end = s1 + s2 ;
cout << s_end << endl;
cout << s1[0] << "----" << s2[0] << endl;
return 0;
}
Hello world MMMMM
H----M
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1;
while (cin >> s1)
{
cout << "s1:" << s1 << endl;
}
return 0;
}
string对象会自动忽略开头的空白,即从第一个真正的字符开始读取,直到遇到第二个空白为止
hello
s1:hello
hello world
s1:hello
s1:world
若要使得保持string对象之间的空白,可使用getline()函数:
int main() {
string s1;
while (getline(cin,s1))
{
cout << "s1:" << s1 << endl;
}
return 0;
}
hello world ! ! !
s1: hello world ! ! ! //开头的空白也会保留
empty()与size()函数
int main() {
string s1;
while (getline(cin,s1))
{
cout << "s1:" << s1 << endl;
cout << "检测是否为空" << s1.empty() << endl;
cout << "string对象的大小 " << s1.size() << endl;
}
return 0;
}
hello world ! ! !
s1: hello world ! ! !
检测是否为空0
string对象的大小 18
循环读取string对象
using namespace std;
string s1 = "999 Hello world ! ! ! 666";
decltype (s1.size()) alpha_cnt = 0, alnum_cnt =0, upper_cnt=0, lower_cnt = 0;
//也可以写为
//string::size_type alpha_cnt = 0, alnum_cnt =0, upper_cnt=0, lower_cnt = 0;
int main() {
for (auto c : s1) {
if (isalpha(c)) {
++alpha_cnt;
}
if (isalnum(c)) {
++alnum_cnt;
}
if (isupper(c)) {
++upper_cnt;
}
if (islower(c)) {
++lower_cnt;
}
}
cout << "string对象中的字母数量为:" << alpha_cnt << endl;
cout << "string对象中的字母与数字数量为:" << alnum_cnt << endl;
cout << "string对象中的大写字母数量为:" << upper_cnt << endl;
cout << "string对象中的小写字母数量为:" << lower_cnt << endl;
return 0;
}
string对象中的字母数量为:10
string对象中的数字数量为:16
string对象中的大写字母数量为:1
string对象中的小写字母数量为:9