C++替换字符串的问题

xg436 2019-03-10 03:55:20
C++string自带的替换只能替换一个,如果想实现替换全部需要自己手动实现,然后自己写了个函数

// Cpp1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "windows.h"
#include <vector>
#include <time.h>

using namespace std;

void replace1(string& input, string search, string replace)
{
int index = input.find(search, 0);
while (index != -1)
{
input = input.replace(index, search.size(), replace);
index = input.find(search, index + replace.size());
}
}
void replace2(string& input, string search, string replace)
{
int index = input.find(search, 0);
vector<int> indexs;
while (index != -1)
{
indexs.push_back(index);
index = input.find(search, index + search.size());
}
vector<char> ret(input.size() + indexs.size() * (replace.size() + search.size()) + 1);
int index1 = 0, index2 = 0;;
for (size_t i = 0; i < indexs.size(); i++)
{
int size = indexs[i] - index1;
if (size > 0)
{
memcpy(&ret[index2], input.c_str() + index1, size);
index2 += size;
index1 += size + search.size();
}
if (replace.size() > 0)
{
memcpy(&ret[index2], replace.c_str(), replace.size());
index2 += replace.size();
}
}
if(input.size() > index1)
{
memcpy(&ret[index2], input.c_str() + index1, input.size() - index1);
}
ret.push_back(0);
input = &ret[0];
}
int main(int argc, char*argv[])
{
string input = "#include<iostream>using namespace std;int main() {DWORD k = ::GetTickCount(); //获取毫秒级数目Sleep(1000);cout << ::GetTickCount() - k << endl;system(";
auto t1 = ::GetTickCount();
for (size_t i = 0; i < 10000; i++)
{
replace1(string(input), "s", "bb");
}
printf("%lld\n", ::GetTickCount() - t1);
t1 = ::GetTickCount();
for (size_t i = 0; i < 10000; i++)
{
replace2(string(input), "s", "bb");
}
printf("%lld\n", ::GetTickCount() - t1);
return 0;
}

本来觉得按replace1需要反复申请空间拷贝内存,效率应该比replace2低,但实际上是1快很多,这是什么原因呢
...全文
157 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
636f6c696e 2019-03-11
  • 打赏
  • 举报
回复
自带的基础函数都是经过优化很多遍的,一般比你自己写的效率要高得多的多
赵4老师 2019-03-11
  • 打赏
  • 举报
回复
无profiler不要谈效率!!尤其在这个云计算、虚拟机、模拟器、CUDA、多核 、多级cache、指令流水线、多种存储介质、……满天飞的时代!
sdghchj 2019-03-11
  • 打赏
  • 举报
回复
为什么replace1需要反复申请空间呢?string和vector的自动扩容都是有一定算法的,比如2倍策略,根据实际字符串长度,可能扩一次就够用了。 而replace2首先申请一个vector,进行各种拷贝最后返回时再调用operator=又一次申请内存加拷贝。两次申请内存妥妥的,代码量还多。

69,336

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧