
23.06.2009, 00:02
|
|
Участник форума
Регистрация: 03.02.2009
Сообщений: 104
Провел на форуме: 270228
Репутация:
70
|
|
Сообщение от rudvil
Воть, обновленная версия реплейсера переписал все с нуля - повышена скорость работы, меньше строчек кода.
Replace (Исходник, НайтиЧто, ЗаменитьЧем);
Пример:
Код:
string hello = "Hello World!";
Replace(hello, "o", "_");
cout << hello << endl;
выведет: Hell_ W_rld!
и ещё
string hello = "Hello Worlld!";
Replace(hello, "ll", "[*]");
cout << hello << endl;
выведет: He[*]o Wor[*]d!
Исходник:
Код:
#include <iostream>
#include <string>
using namespace std;
void Replace (string& source, string find_what, string replace_with) {
if (source == "" || find_what == "") {
return;
}
if (source == find_what) {
source = replace_with;
return;
}
unsigned int findwhat_index = 0,
start_index = 0,
find_length = find_what.length(),
flag = 0;
for (unsigned int i = 0; i < source.length(); i++ ) {
switch (flag) {
case 0:
if (source.at(i) == find_what.at(0) && find_length == 1) {
source = source.replace(i, 1, replace_with);
}
else if (source.at(i) == find_what.at(0)) {
start_index = i;
findwhat_index++;
flag = 1;
}
break;
case 1:
if (source.at(i) == find_what.at(findwhat_index) && findwhat_index < (find_length - 1)) {
findwhat_index++;
}
else if (source.at(i) == find_what.at(findwhat_index) && findwhat_index == (find_length - 1)) {
source = source.replace(start_index, find_length, replace_with);
findwhat_index = 0;
start_index = 0;
flag = 0;
}
else {
findwhat_index = 0;
start_index = 0;
flag = 0;
}
break;
}
}
}
Не считаю хорошей идеей использовать в этой функции тип string ((..
ИМХО лучше реализовать с char;
|
|
|