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

本文展示了一个使用C++进行字符串替换的简单示例。通过读取文件内容,并利用自定义函数replaceAll,将指定字符串从源文件中全部替换为新的字符串,最后将修改后的内容输出到另一个文件中。此示例适用于理解如何在C++中操作字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

///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 ///:~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值