字符串文字而不必转义特殊字符?

时间:2012-01-26 20:39:45

标签: objective-c nsstring escaping string-literals

Objective-c中是否有一个字符串文字形式,不需要转义特殊字符?换句话说,我正在寻找Python三重引用的等价物。

我正在尝试将一些HTML放入NSString,并且希望避免从所有HTML属性中删除引号。

4 个答案:

答案 0 :(得分:3)

在C ++ 11中,你可以这样做。请参阅my answersimilar question

为此你需要在你的情况下Objective-C ++ 11。它应该在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至少编译。

答案 1 :(得分:2)

没有相当于三重报价;字符串文字必须始终对特殊字符使用转义。

最好的办法是将HTML放入与源不同的文件中,然后使用-[NSString initWithContentsOfFile:encoding:error:](或相关的initWithContentsOfURL:...)创建字符串。

答案 2 :(得分:1)

不,不幸的是......在obj-c中有关于字符串文字的一些很好的信息:
http://blog.ablepear.com/2010/07/objective-c-tuesdays-string-literals.html

答案 3 :(得分:0)

对于现在阅读此内容的任何人:

此功能自Swift 4开始实施。请在此处阅读更多相关信息:https://github.com/apple/swift-evolution/blob/master/proposals/0168-multi-line-string-literals.md

你可以这样做:

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