问题
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.
回答1:
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:...).
回答2:
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.
回答3:
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
回答4:
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>
"""
来源:https://stackoverflow.com/questions/9025004/string-literals-without-having-to-escape-special-characters