ios (Swift) 如何在字符串中打印“\”字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30170908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
(Swift) how to print "\" character in a string?
提问by Rahul Sonvane
I have tried to print it but it just by passes because it's an escaped character. e.g output should be as follows.
我试图打印它,但它只是通过,因为它是一个转义字符。例如输出应该如下。
\correct
Thanks in advance
提前致谢
回答by C-JARP
For that and also future reference:
为此以及将来的参考:
let myText = #"This is a Backslash: \"#
print(myText)
– 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.
回答by AtulParmar
Use the following code for Swift 5, Xcode 10.2
对Swift 5, Xcode 10.2使用以下代码
var s1: String = "I love my "
let s2: String = "country"
s1 += "\"\(s2)\""
print(s1)
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
回答by tania_S
It will print I love my "country"
它会打印我爱我的“国家”
回答by matthew.healy
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("\\")
将导致只是\
被打印。