#include <fstream>
#include <sstream>
#include <iostream>
#include <vector>
using namespace std;
void readTxt(string file)
{
ifstream infile;
infile.open(file.data()); //将文件流对象与文件连接起来
assert(infile.is_open()); //若失败,则输出错误消息,并终止程序运行
char ch;
std::vector<std::string> lines;
std::string strLine;
while (!infile.eof())
{
//infile >> c;
infile.get(ch);
if (ch == '\n' || ch == '\n\r') {
lines.push_back(strLine);
//cout << strLine << endl;
strLine.clear();
continue;
}
strLine.push_back(ch);
}
for(size_t i=0;i< lines.size(); i++)
cout << lines[i] << endl;
infile.close(); //关闭文件输入流
}
static std::vector<std::string> parseListFile(const std::string& fileName)
{
std::vector<std::string> lines;
std::ifstream infile(fileName);
if (!infile)
{
return lines;
}
std::string line;
while (getline(infile, line))
{
lines.push_back(line);
}
infile.close();
return lines;
}
static bool isSeparator(const std::string& seps, char c)
{
// seps.size() had been defined as unsigned int
for (size_t i = 0; i < seps.size(); ++i)
{
if (seps[i] == c) return true;
}
return false;
}
static std::vector<std::string> split(const std::string& s, const std::string& seps)
{
std::vector<std::string> ret;
std::string::size_type i = 0;
// invariant: we have processed characters [original value of i, i)
while (i != s.size())
{
// ignore leading blanks
// invariant: chartacters in range [original i, current i) are all spaces
while (i != s.size() && isSeparator(seps, s[i]))
++i;
// find end of next word
std::string::size_type j = i;
// invariant: none of the characters in rang [original j, current j) is a space
while (j != s.size() && !isSeparator(seps, s[j]))
++j;
// if we found some nonewithspace characters
if (i != j)
{
// copy from s starting at i and taking j - i chars
ret.push_back(s.substr(i, j - i));
i = j;
}
}
return ret;
}
static std::vector<std::vector<std::string>> parseTableFile(const std::string& fileName, const std::string& sep)
{
std::vector<std::vector<std::string>> lines;
std::ifstream infile(fileName);
if (!infile)
{
return lines;
}
std::string line;
while (getline(infile, line))
{
//cout << split(line, sep) << endl;
lines.push_back(split(line, sep));
}
infile.close();
return lines;
}
std::string int2str(int val)
{
std::string str;
std::stringstream ss;
ss << val;
return ss.str();
}
int main()
{
string fileName = "a-mei//a-mei_0005.jpg 163.0751 76.10593 166.3308 173.72844";
string sep = "mei";
std::vector<std::string> ret;
ret = split(fileName, sep);
//cout << ret[1] << " " << ret[2] << " " << ret[3] << " " << endl;
size_t index = 0;
while (index != ret.size()){
cout << ret[index] << endl;
++index;
}
getchar();
}
C++实现给定字符的字符串分割
于 2018-12-05 10:13:44 首次发布