Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strip quotes from a string

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

like image 378
Pieter van Wyk Avatar asked Feb 10 '10 17:02

Pieter van Wyk


3 Answers

You can use MyVar := StringReplace(MyVar,'''','',[rfReplaceAll]);

like image 121
skamradt Avatar answered Nov 11 '22 17:11

skamradt


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.)

like image 42
Deltics Avatar answered Nov 11 '22 15:11

Deltics


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.

like image 7
Warren Markon Avatar answered Nov 11 '22 15:11

Warren Markon