Показать сообщение отдельно

  #24  
Старый 07.05.2009, 23:25
rudvil
Участник форума
Регистрация: 25.08.2008
Сообщений: 187
Провел на форуме:
2066562

Репутация: 86
По умолчанию

Воть, обновленная версия реплейсера переписал все с нуля - повышена скорость работы, меньше строчек кода.

replace (Исходник, НайтиЧто, ЗаменитьЧем);

Пример:
Код:
std::string hello = "Hello World!";
replace(hello, "o", "_");
std::cout << hello << "\n";
выведет: Hell_ W_rld!

и ещё

std::string hello = "Hello Worlld!";
replace(hello, "ll", "$");
std::cout << hello << "\n";
выведет: He$o Wor$d!
Исходник:
Код:
#include <iostream>
#include <string>

void replace (std::string& source, std::string findWhat, std::string replaceWith) {
    if (source == "" || findWhat == "")
        return;
    if (source == findWhat) {
        source = replaceWith;
        return;
    }
    size_t findWhatIndex = 0;
    size_t startIndex = 0;
    size_t findLength = findWhat.length();
    bool flag = false;
    for (size_t i = 0; i < source.length(); i++) {
        if (flag) {
            if (source.at(i) == findWhat.at(findWhatIndex) && findWhatIndex < (findLength - 1))
                ++findWhatIndex;
            else if (source.at(i) == findWhat.at(findWhatIndex) && findWhatIndex == (findLength - 1)) {
                source = source.replace(startIndex, findLength, replaceWith);
                findWhatIndex = 0;
                startIndex = 0;
                flag = false;
            }
            else {
                findWhatIndex = 0;
                startIndex = 0;
                flag = false;
            }
        }
        else {
            if (source.at(i) == findWhat.at(0) && findLength == 1)
                source = source.replace(i, 1, replaceWith);
            else if (source.at(i) == findWhat.at(0)) {
                startIndex = i;
                ++findWhatIndex;
                flag = true;
            }
        }
    }
}

Последний раз редактировалось rudvil; 24.02.2010 в 04:14..
 
Ответить с цитированием