以前,针对分解字符串的需求,总是用Qt,最近发现C++一样的。特此记录。
C++版
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <regex>
using namespace std;
int main()
{
string s{"12,-2.3,-1.2e-3;;1023.283784,.12,-.23;"};
regex regex{"([^\\d\\.eE\\-])"};
sregex_token_iterator it{s.begin(), s.end(), regex, -1};
list<string> words{it, {}};
vector<double> values;
for_each(words.begin(),words.end(),[&values](string v){
values.push_back(atof(v.c_str()));
});
for_each(values.begin(),values.end(),[](double v){
cout<<v<<"\n";
});
return 0;
}
Qt 版
#include <QCoreApplication>
#include <QList>
#include <QRegExp>
#include <QStringList>
#include <QTextStream>
#include <QVector>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
const QString str = "12,-2.3,-1.2e-3;;1023.283784,.12,-.23;";
const QStringList lst = str.split(QRegExp("[^\\d\\.eE\\-]"));
QVector<double> vec;
foreach(const QString v, lst)
vec.push_back(v.toDouble());
QTextStream so(stdout);
foreach(auto v, vec)
so << v << "\n";
so.flush();
return 0;
}
输出
12
-2.3
-0.0012
0
1023.28
0.12
-0.23
0
因此,我们在动手前,可以多搜索一下,看看有没有经典的实现。