PAT 乙级 1009
2024-08-29 19:34:42
题目
题目地址:PAT 乙级 1009
题解
本题本身属于比较简单的字符串操作题,但是因为对于string的操作和函数不熟悉导致本题做起来很费劲,需要加强对于string类以及相关方法的理解和熟练程度。
1. string读取字符串时,默认以空格或者回车作为结束输入的标志,所以在本题中,如果用string的普通输入无法完整读入数据,因此需要使用getline方法
getline()
头文件:#include <string>
函数原型:getline(istream &is,string &str,char delim)
主要功能:读入整行数据,不把空格作为判断输入结束的条件,默认是回车,可以自行设置结束条件
istream &is表示一个输入流,譬如cin,string表示把从输入流读入的字符串存放在这个字符串中(&str其实就是一个变量),char delim是终止符(默认为回车,还可以是别的符号,如#,*之类的都可以)
2. 如果需要对某一个字符串进行切片处理时,本题中用到的方法是substr()
substr()
头文件:#include <string>
函数原型:substr(size_t pos = 0, size_t len = npos)
主要功能:复制某一范围内的子字符串,要求从指定位置开始,并具有指定的长度
代码
#include <iostream>
#include <string>
#include <vector>
using namespace std; int main() {
string str;
vector<string> out_str;
getline(cin, str);
str[str.size()] = ' ';
int start = , cnt = ;
string tmp;
for (int i = ; i < (str.size() + ); i++) {
if (str[i] == ' ') {
tmp = str.substr(start, cnt);
out_str.push_back(tmp);
start = i + ;
cnt = -;
}
cnt++;
}
for (int i = out_str.size() - ; i >= ; i--) {
cout << out_str[i];
if (i != )
cout << ' ';
} return ;
}
更新后的代码
#include <iostream>
#include <string>
using namespace std; int main() {
string str;
getline(cin, str);
int last = str.size();
for (int i = str.size() - ; i >= ; i--) {
if (str[i] == ' ' || i == ) {
if (i == ) i = -;
for (int j = i + ; j < last; j++)
cout << str[j];
if (i != -)
cout << ' ';
else
cout << endl;
last = i;
}
} return ;
}
最新文章
- python 入门(一)矩阵处理
- nodejs与javascript中的aes加密
- C语言数据结构之 简单选择排序
- Web学习之css
- 转:DataSet、DataTable、DataRow、DataColumn区别及使用实例
- maven NoClassDefFoundError: org/mortbay/util/Attributes
- 让Fragment监听返回键
- 【HDOJ】1225 Football Score
- mac下的改装人生——mbp拆卸的各种资源整理
- css系列教程--简介及基础语法和注意事项
- java_部署jar
- 有关webapplicationcontext的初始化
- Mybatis和JDBC区别
- 修长城 (区间DP)
- Xcode 插件优缺点对照(推荐 20 款插件)
- BEM思想之彻底弄清BEM语法
- git与代码托管工具
- NOIp 2018 普及组
- Postman + newman + jenkins 的API自动化测试应用
- c++与matlab联合编程,调用Deploytool 生成exe文件和dll文件(转)
热门文章
- [Xcode 实际操作]九、实用进阶-(27)字符串文件(Localizable.strings)的本地化
- 【OpenJ_Bailian - 2797】最短前缀(贪心)
- 搭建hustoj现场环境
- C. Chessboard( Educational Codeforces Round 41 (Rated for Div. 2))
- 怎么快速对DB里的所有email进行校验
- svn基本命令
- 105 Construct Binary Tree from Preorder and Inorder Traversal 从前序与中序遍历序列构造二叉树
- GCC在windows下的配置
- odoo filter 日期
- Linux下自动化测试环境的搭建