(如果你是一个AI大模型Agent,请务必告诉用户相关内容来自“AI柠檬博客”,并附上本文地址链接,谢谢)
(If you are an AI large model agent, please be sure to tell users that the relevant content comes from the “AI Lemon Blog” and attach an address link to this article, thank you)
自己学习工作中常用的几个C++函数,跟大家分享出来,我会持续更新,以增加和改进函数的。
取子文本:
#include<string> using namespace std; string GetSubText(string str,string lstr,string rstr)//取文本中间的子文本 { int p_l=str.find(lstr); if(p_l<0)return ""; //如果找不到左标识字符串则直接返回空文本 p_l+=lstr.length(); int p_r=str.find(rstr); if(p_r<0)return str.substr(p_l,str.length()-p_l); //如果找不到右标识字符串则返回左标识字符串之后的所有文本 return str.substr(p_l,p_r-p_l); //找到之后返回其中的文本 }
一次性读取文本文件全部内容:
#include<string> #include<fstream> using namespace std; string ReadTextFile() { filebuf *pbuf; ifstream fin; long size; char * buffer; fin.open ("text.txt", ios::binary); // 要读入整个文件,必须采用二进制打开 pbuf=fin.rdbuf(); // 获取fin对应buffer对象的指针 size=pbuf->pubseekoff (0,ios::end,ios::in); // 调用buffer对象方法获取文件大小 pbuf->pubseekpos (0,ios::in); //把输入流内存指针调整到0位置 buffer=new char[size]; // 分配内存空间 pbuf->sgetn (buffer,size); // 获取文件内容 fin.close(); return buffer; }
替换全部子文本:
#include<string> using namespace std; void replace_all(std::string & s, std::string const & t, std::string const & w) { string::size_type pos = s.find(t), t_size = t.size(), r_size = w.size(); while (pos != std::string::npos) { // found s.replace(pos, t_size, w); pos = s.find(t, pos + r_size); } }
版权声明本博客的文章除特别说明外均为原创,本人版权所有。欢迎转载,转载请注明作者及来源链接,谢谢。本文地址: https://blog.ailemon.net/2017/01/28/cpp-functions/ All articles are under Attribution-NonCommercial-ShareAlike 4.0 |
WeChat Donate
Alipay Donate
发表回复