【问题标题】:(Swift) how to print "\" character in a string?(Swift)如何在字符串中打印“\”字符?
【发布时间】:2023-03-30 05:42:01
【问题描述】:

我试图打印它,但它只是通过传递,因为它是一个转义字符。 例如,输出应如下所示。

\correct

【问题讨论】:

  • 用另一个反斜杠再次转义:"ab\\cd" 将给出"ab\cd"
  • 记录在 Swift Book 中,并且在对您之前问题的评论中提供了相关章节的链接。
  • 不知道为什么这个问题会得到那些负面反馈,因为它确实对我有帮助。问题是,在操场上时,右侧面板中不会显示双反斜杠

标签: ios swift string escaping slash


【解决方案1】:

为此以及将来的参考:

\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.

【讨论】:

  • 为什么单引号需要转义?
  • @DuncanC 因为编译器无法确定它是字符串结尾还是字符串中的双斜杠
  • in swift 4 "\\" 给你 "\\"
  • 如何快速打印撇号?
【解决方案2】:

Swift 5、Xcode 10.2

使用以下代码
let myText = #"This is a Backslash: \"#
print(myText)

输出:

这是一个反斜杠:\

现在在 swift 5 中不需要添加双斜杠来使用单斜杠,即使现在在某些字符之前也需要斜杠,例如单引号、双引号等。

有关 swift 5 的最新更新,请参阅此帖子

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

【讨论】:

  • 在 Swift 5 上尝试这个,Xcode 11.1 打印出:“这是一个反斜杠:\\”
  • 我使用的是 Swift 5.1,它非常适合我。 Idk 肯定是 Swift 5,但我确信它适用于 Swift 5.1。
【解决方案3】:
var s1: String = "I love my "
 let s2: String = "country"
   s1 += "\"\(s2)\""
   print(s1)

它会打印出我爱我的“国家”

【讨论】:

    【解决方案4】:

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

    【讨论】:

    • 感谢 Eric 的教育,并为这样的菜鸟错误感到抱歉。我一直依赖 Playground 右侧的输出,但从未使用过该底部面板。灯泡现在已经点亮。你一定是mod?我开始了关于这个主题的另一个线程,它可能也应该死掉。
    猜你喜欢
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    相关资源
    最近更新 更多