StrSubstr
/*
* File: strSubst.cpp
* Author: borovec
*
* Created on 18. listopad 2008, 17:49
*/
#include <iostream>
using namespace std;
bool isSearchStr(const char * Where, const char * Search){
if(strlen(Search)==0) return (false);
while(*Search!='\0'){
if(*Search!=*Where) return (false);
Where++;
Search++;
}
return (true);
}
char * reallocArray(char * array, int &len, int newlen){
char * newArray = new char[newlen];
if(len<newlen) len = newlen;
for (int i = 0; i < len; i++) {
newArray[i] = array[i];
}
delete [] array;
return newArray;
}
char * strSubst ( const char * Where, const char * Search, const char * Replace )
{
const int lenWhere = strlen(Where);
const int lenSearch = strlen(Search);
const int lenReplace = strlen(Replace);
int lenNewString = lenWhere;
char *newString = new char [lenWhere];
int pos = 0;
while(*Where!='\0'){
if(isSearchStr(Where,Search)){
newString = reallocArray(newString, lenNewString, (lenNewString)+(lenReplace-lenSearch));
const char * Rep_bak = Replace;
while(*Rep_bak!='\0'){
newString[pos] = *Rep_bak;
Rep_bak++;
pos++;
}
Where += lenSearch;
continue;
}
newString[pos] = *Where;
pos++;
Where++;
}
newString[pos] = '\0';
return newString;
}
/*
*
*/
int main(int argc, char** argv) {
cout << strSubst ( "Kozino, Kozino, do roka a do dne ...", "Kozino", "Lomikare" ) << endl;
cout << strSubst ( "ahojahoj", "ahoj", "ahojahoj" ) << endl;
// ret -> "ahojahojahojahoj"
cout << strSubst ( "+*[]*++*[]*+test+*[]*++*[]*+", "+*[]*+", "" ) << endl;
// ret -> "test"
cout << strSubst ( "aaa", "aa", "b" ) << endl;
// ret -> "ba"
cout << strSubst ( "aaa", "", "b" ) << endl;
// ret -> "aaa"
cout << strSubst ( "Kozino, Kozino, do roka a do dne ...", "", "" ) << endl;
// ret -> "test"
return (EXIT_SUCCESS);
}