Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringReplace fails to replace all instances of a string

Tags:

replace

delphi

The Dephi 7 help manual says of StringReplace...

Returns a string with occurrences of one substring replaced by another substring...

If Flags does not include rfReplaceAll, StringReplace only replaces the first occurrence of OldPattern in S. Otherwise, StringReplace replaces all instances of OldPattern with NewPattern.

The statement that, "Otherwise, StringReplace replaces all instances of OldPattern with NewPattern" appears to be a BOGUS statement, for in the example below, instances of "aa" remain even after I instruct the function to "replace all instances of 'aa' (OldPattern) with 'a' (NewPattern)"!

StringReplace('aaa aaa','aa','a',[rfReplaceAll]);

If the Delphi manual was accurate, then I should be getting 'a a' as the final result. Unfortunately, I am getting 'aa aa'. Clearly not all instances of "OldPattern" ('aa') were replaced.

Is this a bug, or simply a misleading/inaccurate description for the function?

like image 557
user1527613 Avatar asked Dec 03 '22 22:12

user1527613


1 Answers

You have misunderstood the documentation. If the act of replacing an instance of the search string with the replacement happens to create another instance of the search string, it is not searched again. The search continues from the end of the replacement text.

The function searches for all instances of the target string in the input string S. The input string is not modified. To get the output you expected, it would have to search for instances of the target string in the result, not just in the input.

Imagine if the search and replacement strings were identical. The function might never return because each time it found its target and replaced it, it would find yet another copy of the target text.

like image 170
Rob Kennedy Avatar answered Dec 05 '22 11:12

Rob Kennedy