Free Pascal => Beginners => Topic started by: JLWest on November 13, 2019, 05:23:46 am
Title: String Function Question
Post by: JLWest on November 13, 2019, 05:23:46 am
Is there a string function to replace a character in a string with something else? Trying to make the following work but it doesn't make the changes in Bit1;
Note that the latter only works for single char replacements, but it will replace all occurrences..
(I wonder where your original idea/code comes from? It is definitely not yours...but from somewhere else? Trying to translate?)
Title: Re: String Function Question
Post by: JLWest on November 24, 2019, 07:23:32 am
@Thaddy your right.
I tried to adapt 'function Count(What, InWhat: String): Integer; ' to what I needed.
I got my function working by changing the 1 to i.
However I think the s.Replace('b','t',[rfReplaceAll])); is very elegant and I need to change to that.
Thanks.
Title: Re: String Function Question
Post by: Birger52 on December 05, 2019, 05:50:40 pm
Just a not to StringReplace. Had a situation with importing files, where someone went overboard with the enter button, to create new lines, so there could be more than for #13's in a row... [rfReplaceAll] is not recurive, so StringReplace(aString, #13#13, #13, [rfReplaceAll]) will only replace from the original - not with the charaters replaced. A string with #13#13#13# or 13#13#13#13 would contain #13#13 after replacement So constructions like while Pos(#13#13, aString) do aString := StringReplace(aString, #13#13, #13, [rfReplaceAll]) may be needed
Title: Re: String Function Question
Post by: lucamar on December 05, 2019, 06:30:54 pm
For future generations :) , you meant "Just a note ...", didn't you?
It's a good note: StringReplace() does a single pass, jumping over recently replaced strings so it must be called in a while (or similar) loop to replace recursively.
Title: Re: String Function Question
Post by: Zvoni on December 06, 2019, 12:34:06 pm
There is quite a "nasty" trick to solve the problem of consecutive characters you'd like to trim down: Split the String! https://www.freepascal.org/docs-html/rtl/sysutils/tstringhelper.split.html and use Option "ExcludeEmpty" https://www.freepascal.org/docs-html/rtl/sysutils/tstringsplitoptions.html Then join the Array back together
Another way would be to run a string from its end to its start (maybe using a pointer), first comparing position i with searched character, if yes then compare with position i+1, if equal copy ("move") pointer i+1 to i