现在的位置: 首页 > 综合 > 正文

《Thinking in c++》第二册 ————3_6

2013年08月02日 ⁄ 综合 ⁄ 共 783字 ⁄ 字号 评论关闭

///fromTo.cpp

//将文件中所有的from(被替换字符串) 替换成 to(替换后的字符串),然后输出到另一个文件

#include <string>
#include <cstddef>
#include <sstream>
#include <fstream>
#include <iostream>
#include "ReplaceAll.h"
using namespace std;

 

int main(){
 ifstream in("Wowbull.cpp");
    ostringstream oss;
 oss << in.rdbuf();
 string s = oss.str();
 istringstream ins(replaceAll(s,"from","to"));
    ofstream out("www.cpp");
    out << ins.str();
 return 0;
}

 

///ReplachAll.h

#ifndef REPLACEALL_H
#define REPLACEALL_H

#include <string>
#include <cstddef>

using namespace std;

std::string& replaceAll(std::string & context, const std::string& from, const std::string & to){
 size_t lookHere = 0;
 size_t foundHere;
 while((foundHere = context.find(from,lookHere))!= string::npos){
  context.replace(foundHere,from.size(),to);
  lookHere = foundHere + to.size();
 }
 return context;
}

#endif //REPLACEALL_H ///:~

抱歉!评论已关闭.