Скачиваний:
31
Добавлен:
02.05.2014
Размер:
2.42 Кб
Скачать
#include "iostream.h"
#include "string.h"
#include "stdio.h"

char* getSubstring( char string[], int first, int last ){
	char* res;
	int i;
	if ( first > last || last > (int)strlen( string ) ){
		if ( first > last ){
            res = ""; printf(" first position must be <= last position ");
        } else {
            res = ""; printf(" last position must be < length(str) ");
		}
	} else {
		res = new char[last - first + 1];
		res[last - first + 1] = '\0';
        for ( i = 0; i < last - first + 1; i ++ ) {
            res[i] = string[first + i];
        }
    }
    return res;
}

bool equals( char str1[], char str2[] ){
	int i;
    if ( strlen(str1) != strlen(str2) ) {
		return false;
    } else {
		for ( i = 0; i < (int) strlen(str1); i ++ ) {
			if ( str1[i] != str2[i] ) {
				return false;
			}
        }
	}
    return true;
}

char* concatenate( char str1[], char str2[] ){
	char *res;
	int i,ls1,ls2;
    ls1 = strlen(str1);
    ls2 = strlen(str2);
	res = new char[ls1 + ls2 + 1];
	for ( i = 0; i < ls1; i ++ ){
		res[i] = str1[i];
	}
    for ( i = 0; i < ls2; i ++ ){
		res[ls1 + i] = str2[i];
	}
	res[ls1 + ls2] = '\0';
    return res;
}

char* replace( char str[], char oldsubstr[], char newsubstr[] ){
	int i, osl, sl, maxL = 1000;
    char* resultat;
    resultat = new char[maxL];
	resultat[0] = '\0';
    i = 0;
    sl = strlen(str);
    osl = strlen(oldsubstr);
    if ( osl == 0 ) { cout << "Old Substring must have length > 0"; return str; }
	while ( i <= sl - osl ){
		if ( equals( oldsubstr, getSubstring( str,i,i + osl - 1 ) ) ){
			resultat = concatenate(resultat,newsubstr);
			i = i + osl;
		} else { 
            resultat = concatenate(resultat, getSubstring(str,i,i));
            i ++;
		}
	}
    if ( i < sl ) {
		resultat = concatenate(resultat,getSubstring(str,i,sl-1)); 
	}
	resultat[strlen(resultat)] = '\0';
    return resultat;
}

void main(){
	int maxL = 10000;
	char *str, *oldsubstr, * newsubstr;
	str = new char[maxL];
	oldsubstr = new char[maxL];
	newsubstr = new char[maxL];
    cout << "Find And Replace Algoritm.\nEnter string: ";
    cin >> str;
    cout << "Enter OldSubstring: "; 
	cin >> oldsubstr;
    cout << "Enter NewSubstring: "; 
	cin >> newsubstr;
    cout << "Result: " << replace(str,oldsubstr,newsubstr) << "\nPress any key to continue..." << endl; 
    getchar();
}