Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickie - replace all occurrences of ' (apostrophe) with '' (two apostrophes) in an AnsiString (C++)

I think you can guess the problem I'm having. I'm inserting filenames in to an sql database in C++ Builder. Some files have an apostrophe in their name. This breaks the sql insert query. the usual way to fix this is to double up and apostrophes you want to be part of the field value.

For example if I want to add 'george's' to field 'owner' the sql query would be "insert into table (owner) values ('george''s')"

I'm ok with that bit. I just need to get the single apostrophes replaced with double ones. AnsiString doesn't seem to have a built in function for this. Is there a simple way to do it without having to include a whole new header file?

like image 864
MrVimes Avatar asked Jan 21 '09 01:01

MrVimes


2 Answers

Actually I got the answer by myself...

item = StringReplace( item, "'", "''", TReplaceFlags() <<rfReplaceAll );

(so there is a built in replace function in AnsiString afterall)

Edit: Added code tags so we can distinguish between different quotes

like image 126
MrVimes Avatar answered Nov 04 '22 08:11

MrVimes


I haven't used AnsiString, but basically I'd do the following:

  • Reverse find single quotes in your string
  • Look to the left and right of the current single quote index
  • If there's not a single quote there already, insert a single quote after your current index
  • Continue looping until you hit index 0.
like image 1
Eddie Parker Avatar answered Nov 04 '22 08:11

Eddie Parker