第三章 字符串、向量和数组
命名空间的using声明
使用using就不需要前缀。没使用using前,在函数中使用cin,写法:std::cin,在函数前使用语句using std::cin,在函数中只需写cin即可。
标准库类型string
初始化分两种,拷贝初始化和直接初始化。
string s1 = "hello"; //拷贝初始化
string s2 = ("hello"); //直接初始化
string对象上的操作
读写:cin读,cout写。
读未知数量对象:while(cin >> word)
读取一整行:用getline,while(getline(cin,line))
用string会跳过前面的空白,从第一个真正的字符开始,直到遇到下一个空白。
getline函数是一个输入流和一个string对象,从给定的输入流读入内容,直到遇到换行符。
empty和size:empty判空,size返回string对象长度
比较:==,!=, <, >, <=, >=
赋值:s1 = s2
相加:s1 + s2 。允许字符字面值和字符串字面值混合相加,但+两侧至少有一个字符串字面值,运算顺序从左至右 。
练习:
3.2
#include<iostream>
#include<string>
using std::string;
using std::getline;
using std::cin;
using std::cout;
using std::endl;
int main()
{
string line;
while (getline(cin,line))
{
cout << line << endl;
}
return 0 ;
}
//修改
int main()
{
string line;
cin >> line;
cout << line << endl;
return 0 ;
}
3.4f
#include<iostream>
#include<string>
using std::getline;
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main()
{
string s1,s2;
cin >> s1 >> s2;
if (s1 == s2)
{
cout << s1 << s2 << endl;
}
else {
if (s1 <= s2)
{
cout << s2 << endl;
}
else {
cout << s1 << endl;
}
}
return 0;
}
3.5
#include<iostream>
#include<string>
using std::getline;
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main()
{
string word, phase;
cin >> word;
phase = word + " ";
while (cin >> word)
{
phase = phase + word + " ";
}
cout << phase << endl;
return 0;
}
处理string对象中的字符
范围for语句
基本形式:
for (declaration : expression)
statement
应用举例
string str("hello world");
for (auto &c : str)
{
cout << c << endl;
}
下标运算符
设一个字符串str(“hello world”),str[i],i=0,1,2,...代表字符串str的第i+1个字符。
应用举例
string str("hello world");
str[0] = 'H';
cout << str << endl;
输出结果为Hello world。
练习:
3.6
#include<iostream>
#include<string>
using std::cout;
using std::endl;
using std::string;
int main()
{
string str("hello world");
for (auto& c : str)
c = 'X';
cout << str << endl;
return 0;
}
3.7
#include<iostream>
#include<string>
using std::cout;
using std::endl;
using std::string;
int main()
{
string str("hello world");
for (string::size_type i = 0; i < str.size(); ++i)
{
str[i] = 'X';
}
cout << str << endl;
return 0;
}
#include<iostream>
#include<string>
using std::cout;
using std::endl;
using std::string;
int main()
{
string str("hello world");
string::size_type i = 0;
while (str[i] != '\0')
{
str[i] = 'X';
i++;
}
cout << str << endl;
return 0;
}
3.10
#include<iostream>
#include<string>
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main()
{
string str_in, str;
cin >> str_in;
for (auto c : str_in)
{
if (!ispunct(c))
{
str = str + c;
}
}
cout << str << endl;
return 0;
}
练习参考:C++Primer第五版 习题答案 目录_shamozhizhoutx的博客-CSDN博客
学习资料:《C++Primer》