69,336
社区成员
发帖
与我相关
我的任务
分享
// 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;
}