简体   繁体   English

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

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

I have tried to print it but it just by passes because it's an escaped character.我试图打印它,但它只是通过,因为它是一个转义字符。 eg output should be as follows.例如输出应该如下。

\correct

For that and also future reference:为此以及将来的参考:

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

Use the following code for Swift 5, Xcode 10.2Swift 5, Xcode 10.2使用以下代码

let myText = #"This is a Backslash: \"#
print(myText)

Output:输出:

This is a Backslash: \\这是一个反斜杠:\\

Now not required to add a double slash to use a single slash in swift 5, even now required slash before some character, for example, single quote, double quote etc.现在不需要在 swift 5 中添加双斜杠来使用单斜杠,即使现在需要在某些字符前加斜杠,例如单引号、双引号等。

See this post for latest update about swift 5有关 swift 5 的最新更新,请参阅此帖子

https://www.hackingwithswift.com/articles/126/whats-new-in-swift-5-0 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)

It will print I love my "country"它会打印我爱我的“国家”

The backslash character \\ acts as an escape character when used in a string.在字符串中使用时,反斜杠字符\\充当转义字符。 This means you can use, for example, double quotes, in a string by pre-pending them with \\ .这意味着您可以在字符串中使用例如双引号,方法是在它们前面加上\\ The same also applies for the backslash character itself, which is to say that println("\\\\") will result in just \\ being printed.这同样适用于反斜杠字符本身,也就是说println("\\\\")将导致仅打印\\

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM