(Swift)如何在字符串中打印"\"字符?

Rah*_*ane 11 string xcode slash ios swift

我试图打印它,但它只是通过,因为它是一个逃脱的角色.例如,输出应如下.

\correct
Run Code Online (Sandbox Code Playgroud)

提前致谢

小智 52

为了这个以及将来的参考:

\0 – Null character (that is a zero after the slash)
\\ – Backslash itself.  Since the backslash is used to escape other characters, it needs a special escape to actually print itself.
\t  – Horizontal tab
\n – Line Feed
\r  – Carriage Return
\”  – Double quote.  Since the quotes denote a String literal, this is necessary if you actually want to print one.
\’  – Single Quote.  Similar reason to above.
Run Code Online (Sandbox Code Playgroud)

  • 迅速4“ \\”给你“ \\” (4认同)

小智 6

var s1: String = "I love my "
 let s2: String = "country"
   s1 += "\"\(s2)\""
   print(s1)
Run Code Online (Sandbox Code Playgroud)

它将打印我爱我的“国家”


mat*_*aly 5

反斜杠字符\在字符串中使用时充当转义字符。这意味着您可以在字符串中使用双引号,只需在它们前面加上\. 这同样适用于反斜杠字符本身,也就是说,这println("\\")将导致仅\被打印。


Atu*_*mar 5

将以下代码用于Swift 5,Xcode 10.2

let myText = #"This is a Backslash: \"#
print(myText)
Run Code Online (Sandbox Code Playgroud)

输出:

这是一个反斜杠:

现在不需要在swift 5中添加双斜杠以在单字符中使用单斜杠,甚至现在在某些字符(例如单引号,双引号等)之前也需要斜杠。

查看此帖子以获取有关swift 5的最新更新

https://www.hackingwithswift.com/articles/126/whats-new-in-swift-5-0

  • 在 Swift 5 上尝试此操作,Xcode 11.1 打印出:“This is a Backslash: \\” (3认同)