String literals without having to escape special characters?

大城市里の小女人 提交于 2019-12-10 13:16:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!