Wednesday, March 25, 2009

Escaping Quotes

I've got a very simple tip today, one that I thought most REALbasic developers knew, but I'm finding many actually don't know this.

Let's say you need to put quotes inside a string. The most common way I've seen developers do this is with Chr(34):

  dim myString as string = "Hello " + chr(34) + "World" + chr(34)

Some developers choose to define a constant and use that instead:

  dim myString as string = "Hello " + kQuote + "World" + kQuote

But did you know you can insert a quote into your string by using two quotes instead?

  dim myString as string = "Hello ""World"""

Makes the string a little more legible, doesn't it?


JeremK said...

Thanks for the tip!

Anonymous said...

I read somewhere that you can get into trouble with SQLlite if you use double quotes on SQL statements. Is it better to use:?
dim name as String


sql="Select * from mytable where first_name='"+name+"'"

just a thought.

Tim Hare said...

"Makes the string a little more legible, doesn't it?"

No, it doesn't, IMO. There's a reason some of use use a constant.

But, to each his own.

Thom McGrath said...

Of course, but most people I've seen using constants or chr(34) simply didn't realize typing the quote twice was an option.

Darkstar7 said...

Will a backslash work as well, like in Perl?

e.g. "Hello \"World\""

Peter Fargo said...

It is great for a small example like you posted but I find if I am concatenating a large string with a lot of quotes syntax errors are much easier to figure out with a constant.

I use both depending on complexity. Good for folks to know they have the option :^)

Chris Musty said...

Was starting to wonder why some projects had 2 quotes at the begining of a word and 3 at the end. Thanks!