码迷,mamicode.com
首页 > 编程语言 > 详细

字符串过滤,排序输出数字的问题

时间:2018-08-05 14:24:44      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:end   输出   etl   ecs   code   移动   algo   namespace   send   

/*
题目:
写一个排序程序
输入字符串: "5 34 7 34 6 2 12 3 4, 52 ; 13"
输出字符串: "2 3 4 5 6 7 12 13 34 34 52"
*/
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <sstream>
using namespace std;

int str2num(string s)    //字符串转化为数字的函数(好方法)
{
    int num;
    stringstream ss(s);
    ss >> num;
    return num;
}

int main()
{
    string str;
    string dealedstr;
    vector<string> vecStr;
    vector<int> vecInt;
//获取输入一行字符串 看到网上写的while(getline(cin, str)),这是为了可以重复运行 getline(cin, str);
for (int i = 0; i < str.size(); i++) { if (!((str[i] >= 0) && (str[i] <= 9))) { str[i] = ; //并不存在‘‘这样的字符 } }
str.push_back(
); //为了方便处理最后一个数字(nice) //确定数字子字符串的起止位置. int posBegin = 0; int posEnd = 0; bool boolBegin = false; for (int i = 0; i < str.size();) { if ((str[i] >= 0) && (str[i] <= 9)) { posBegin = i; boolBegin = true; } posEnd = str.find(" ", i); //find(查找字符,查找起点),它不受for循环的影响,直接从位置i开始,返回目标字符首次出现的位置 if ((posEnd > posBegin) && (boolBegin)) //使得posBegin指向新的数字时,vecStr才会进行将其收录进去 { vecStr.push_back(str.substr(posBegin, posEnd - posBegin)); //substr(起始位置,长度) i = posEnd + 1; //i直接跳到posEnd的后一位,避免多位数字时posBegin逐位移动,取到数字的中间位置而出错 } else i++; //不符合条件时,也要进行自增,否则会进入死循环 boolBegin = false; } for (int i = 0; i < vecStr.size(); i++) { vecInt.push_back(str2num(vecStr[i])); } sort(vecInt.begin(),vecInt.end());  //vector的sort函数用法 for (int i = 0; i < vecInt.size(); i++) { cout << vecInt[i] << " "; } cout << endl; system("pause"); return 0; }

 

字符串过滤,排序输出数字的问题

标签:end   输出   etl   ecs   code   移动   algo   namespace   send   

原文地址:https://www.cnblogs.com/Stephen-Qin/p/9425144.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!