简体   繁体   中英

String literals without having to escape special characters?

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.

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.

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

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

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>
"""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM