6

Is there a string literal form in Objective-c that does not require escaping special characters? In other words, I'm looking for an equivalent to the Python triple quote.

I'm trying to put some HTML into an NSString, and would like to avoid having to escape the quotes from all the HTML attributes.

jscs
  • 63,694
  • 13
  • 151
  • 195
pepsi
  • 6,785
  • 6
  • 42
  • 74
  • 1
    You could use single quotes in your HTML to avoid having to escape them. – omz Jan 26 '12 at 20:45
  • In C++11 you can do this. See [my answer][1] to a [similar question][2]. This you require in your case Objective-C++11. It should work though. [1]: http://stackoverflow.com/questions/1135841/c-multiline-string-literal/5460235#5460235 [2]: http://stackoverflow.com/questions/1135841/c-multiline-string-literal – emsr Jan 27 '12 at 16:43
  • Just a note, "triple-quote" has been implemented since Swift 4, see: https://stackoverflow.com/a/47567770/897465 – netdigger Nov 30 '17 at 07:13

4 Answers4

3

In C++11 you can do this. See my answer to a similar question.

For this you require in your case Objective-C++11. It should work though in gcc.

const char * html = R"HTML(
<HTML>
 <HEAD>
   <TITLE> [Python-Dev] Triple-quoted strings and indentation
   </TITLE>
 </HEAD>
 <BODY BGCOLOR="#ffffff">
  blah blah blah
 </BODY>
</HTML>
)HTML";

int
main()
{
}

g++ -std=c++0x -o raw_string raw_string.mm at least compiles.

Community
  • 1
  • 1
emsr
  • 15,539
  • 6
  • 49
  • 62
2

There's no equivalent to the triple-quote; string literals must always use escapes for special characters.

Perhaps the best thing to do would be to put your HTML into a file separate from your source, then create the string using -[NSString initWithContentsOfFile:encoding:error:] (or the related initWithContentsOfURL:...).

jscs
  • 63,694
  • 13
  • 151
  • 195
1

Nope, unfortunately not ... there's some great info on string literals in obj-c here:
http://blog.ablepear.com/2010/07/objective-c-tuesdays-string-literals.html

Joel Martinez
  • 46,929
  • 26
  • 130
  • 185
0

For anyone reading this now:

This feature has been implemented since Swift 4. Read more about it here: https://github.com/apple/swift-evolution/blob/master/proposals/0168-multi-line-string-literals.md

You can do:

let author = "Im the author!"
let x = """
    <?xml version="1.0"?>
    <catalog>
        <book id="bk101" empty="">
            <author>\(author)</author>
            <title>XML Developer's Guide</title>
            <genre>Computer</genre>
            <price>44.95</price>
            <publish_date>2000-10-01</publish_date>
            <description>An in-depth look at creating applications with XML.</description>
        </book>
    </catalog>
"""
netdigger
  • 3,659
  • 3
  • 26
  • 49