Txt-Search replace dynarray of char

From Vectorlab
Jump to: navigation, search


Function to search replace a dynarray of char (strings longer than 255 chars). By Orso B. Schmid


{ Orso *********************************************** }
{ search replace in a given string, big text items }
{ warning! this can output an empty string! }
PROCEDURE T_SearchReplaceXXL(sourceStr, searchStr, replStr: DYNARRAY[] OF CHAR; VAR resultStr: DYNARRAY[] OF CHAR);
	VAR
		tempSource, ready : DYNARRAY[] OF CHAR;
		posInStr : INTEGER;
		
	BEGIN
		ready := '';
		tempSource := '';
		resultStr := '';
		tempSource := sourceStr;
			
		{ search replacing something like that: 'mmmmm','mm', 'mmm'
		produces a nice endless loop without double storing the var }
		
		WHILE (Pos(searchStr, tempSource) > 0) DO BEGIN
		
			{ insert Delete was breaking on empty strings }
			IF (searchStr = tempSource) & (replStr = '') THEN
				tempSource := ''
				
			ELSE BEGIN
				posInStr := Pos(searchStr, tempSource);
				
				IF posInStr = 1 THEN
					ready := Concat(ready, replStr)
				ELSE
					ready := Concat(ready, Copy(tempSource, 1, posInStr-1), replStr);
					
				tempSource := Copy(tempSource, posInStr + Len(searchStr), Len(tempSource));
				{ even if it's longer than the rest of the string, doesn't matter }
			END;
		END;
		
		resultStr := Concat(ready, tempSource);
	END;