题目

题目地址: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 ;
}

最新文章

  1. python 入门(一)矩阵处理
  2. nodejs与javascript中的aes加密
  3. C语言数据结构之 简单选择排序
  4. Web学习之css
  5. 转:DataSet、DataTable、DataRow、DataColumn区别及使用实例
  6. maven NoClassDefFoundError: org/mortbay/util/Attributes
  7. 让Fragment监听返回键
  8. 【HDOJ】1225 Football Score
  9. mac下的改装人生——mbp拆卸的各种资源整理
  10. css系列教程--简介及基础语法和注意事项
  11. java_部署jar
  12. 有关webapplicationcontext的初始化
  13. Mybatis和JDBC区别
  14. 修长城 (区间DP)
  15. Xcode 插件优缺点对照(推荐 20 款插件)
  16. BEM思想之彻底弄清BEM语法
  17. git与代码托管工具
  18. NOIp 2018 普及组
  19. Postman + newman + jenkins 的API自动化测试应用
  20. c++与matlab联合编程,调用Deploytool 生成exe文件和dll文件(转)

热门文章

  1. [Xcode 实际操作]九、实用进阶-(27)字符串文件(Localizable.strings)的本地化
  2. 【OpenJ_Bailian - 2797】最短前缀(贪心)
  3. 搭建hustoj现场环境
  4. C. Chessboard( Educational Codeforces Round 41 (Rated for Div. 2))
  5. 怎么快速对DB里的所有email进行校验
  6. svn基本命令
  7. 105 Construct Binary Tree from Preorder and Inorder Traversal 从前序与中序遍历序列构造二叉树
  8. GCC在windows下的配置
  9. odoo filter 日期
  10. Linux下自动化测试环境的搭建