How do I strip Quotes from a string using Delphi?
Ex. I need to remove all the quotes from 'A','B','C','D', giving a result of A,B,C,D. I've tried
MyVar := jclStrings.StrRemoveChars(sRegions, [#34]);
but no luck so far.
Thanks, Pieter
You can use MyVar := StringReplace(MyVar,'''','',[rfReplaceAll]);
Although the other answers are all viable alternatives, the reason your specific code is not working is due to a simple mistake in the character code:
MyVar := jclStrings.StrRemoveChars(sRegions, [#34]);
The char code #34 represents the double quote char : "
What you need to remove are single quote/apostrophes: '
This has the character code #39, so this simple change should fix your original code:
MyVar := jclStrings.StrRemoveChars(sRegions, [#39]);
A simple way to avoid this sort of confusion is to use the literal char, rather than the char code (it will also make your code easier to read/understand later as you won't have to try to remember what char the code is supposed to represent - you could add a comment of course, but then that comment has to be kept up to date if you change the behaviour of the code itself... I personally prefer self documenting code as far as possible. But I digress).
Since the single quote char is used to delimit a char literal, an embedded single quote within a literal is represented as 2 consecutive single quotes:
MyVar := jclStrings.StrRemoveChars(sRegions, ['''']);
(NOTE: In Delphi 2010 I seem to recall that strings may now be delimited with either single or double quote chars, although I do not recall off-hand whether this extends to char literals (as distinct from single character strings. If so then this char literal could instead be expressed as "'", though whether you find this less or more confusing is a matter of personal preference. For myself I consider it less than sensible to mix string delimiters. Consistency is a great aid to accuracy in my experience.)
You can use StrUtils.ReplaceText.
implementation
Uses StrUtils;
{$R *.dfm}
procedure TGeneric.Button1Click(Sender: TObject);
Var
S: String;
begin
S := '''A'',''B'',''C'',''D''';
S := ReplaceText(S, '''', '');
ShowMessage(S);
end;
S now equals 'A,B,C,D'.
ReplaceText will call AnsiReplaceText which in turn calls SysUtils.StringReplace with the replace flags [rfReplaceAll, rfIgnoreCase] set for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With