簡體   English   中英

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

[英](Swift) how to print “\” character in a string?

我試圖打印它,但它只是通過,因為它是一個轉義字符。 例如輸出應該如下。

\correct

為此以及將來的參考:

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

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

var s1: String = "I love my "
 let s2: String = "country"
   s1 += "\"\(s2)\""
   print(s1)

它會打印我愛我的“國家”

在字符串中使用時,反斜杠字符\\充當轉義字符。 這意味着您可以在字符串中使用例如雙引號,方法是在它們前面加上\\ 這同樣適用於反斜杠字符本身,也就是說println("\\\\")將導致僅打印\\

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM