送给大家一个东西~常用代码(1)
dot99 2004-10-26 03:12:12 跟VB里面的split()函数差不多
不过功能比那个强~~使用也方便~
大家运行一下test-app就知道用法咯
//lnpraser.h
#pragma once
#ifndef LNPHRASER_H
#define LNPHRASER_H
#include <string>
namespace code_garage
{
//class T must have member function / data member followed
// T::size_type
// T::npos
// T::assign(const T&, typename T::size_type)
// T::find_first_not_of(const T&, typename T::size_type)
// T::find_first_of(const T&, typename T::size_type)
template <class T>
class lnphraser
{
private:
T line_;
typename T::size_type pos_;
public:
//不允许空构造
lnphraser(void);
//构造函数
explicit lnphraser(const T& line, typename T::size_type pos = 0)
: line_(line), pos_(pos)
{
void(0);
}
//重新以T初始化
void assign(const T& line, typename T::size_type pos = 0)
{
line_.assign(line);
pos_ = pos;
}
//以分隔符得到下一个token
T operator()(const T& splits)
{
typename T::size_type pl = line_.find_first_not_of(splits, pos_);
if (pl != T::npos) {
typename T::size_type len = line_.find_first_of(splits, pl) - pl;
pos_ = pl + len;
if (pos_ != T::npos) ++pos_;
if (pos_ >= line_.size()) pos_ = T::npos;
return line_.substr(pl, len);
}
return T();
}
#ifdef _DEBUG_
template<class S>
void dump(S& s)
{
s << line_;
}
#endif // _DEBUG_
};
//这是一个string实例化模板
class lnphraser_string : public lnphraser<std::string>
{
public:
lnphraser_string(void);
explicit lnphraser_string(const std::string& line, std::string::size_type pos = 0)
: lnphraser<std::string>(line, pos)
{
void(0);
}
};
}
#endif
//测试程序 test-app.cpp
#include <iostream>
#include <string>
#include "lnpraser.h"
int main(int agrc, char* agrv[])
{
std::cout << "this is a test for code_garage." << std::endl;
std::cout << "now test code_garage::lnphreaser" << std::endl;
std::string ln("some thing \t\nlike this must be phrased");
std::string splits(" \t\n"); //分隔符
code_garage::lnphraser_string lnp(ln);
std::cout << "\n\n" << std::endl;
lnp.dump(std::cout);
std::cout << "\ntest dump() over\n\n" << std::endl;
std::string tmp;
tmp = lnp(splits);
while(!tmp.empty()) {
std::cout << tmp << '\n';
tmp = lnp(splits);
}
std::cout << "operator() testing over\n\n" << std::endl;
std::string ln2("又 是 \n\n 一个\t测试");
lnp.assign(ln2, 2);
lnp.dump(std::cerr);
std::cerr << "\ntesting dump on std::cerr over\n\n" << std::endl;
tmp = lnp(splits);
while(!tmp.empty()) {
std::cout << tmp << '\n';
tmp = lnp(splits);
}
std::cout << "assign testing over\n\n" << std::endl;
lnp.assign(ln, 0);
std::cout << lnp(splits) << '\n';
std::cout << lnp(splits) << std::endl;
code_garage::lnphraser<std::string> lnp2 = lnp;
std::cout << lnp2(splits) << '\n';
std::cout << lnp2(splits) << '\n';
std::cout << "bookmark testing over" << std::endl;
std::cout << "\n\nliblnphraser testing over!!\n\n" << std::endl;
int dummy;
std::cin >> dummy;
return 0;
}
gcc 3.4.x编译通过, vc.net编译通过