我怎么能把一个字符串分成多行如下?
var text:String = "This is some text
over multiple lines"
Run Code Online (Sandbox Code Playgroud)
Con*_*nor 405
Swift 4包括对多行字符串文字的支持.除了换行符,它们还可以包含未转义的引号.
var text = """
This is some text
over multiple lines
"""
Run Code Online (Sandbox Code Playgroud)
较旧版本的Swift不允许您在多行上使用单个文字,但您可以在多行中一起添加文字:
var text = "This is some text\n"
+ "over multiple lines\n"
Run Code Online (Sandbox Code Playgroud)
mco*_*ell 31
我在String上使用了一个扩展来实现多行字符串,同时避免编译器挂起bug.它还允许您指定分隔符,以便您可以像Python的连接函数一样使用它
extension String {
init(sep:String, _ lines:String...){
self = ""
for (idx, item) in lines.enumerated() {
self += "\(item)"
if idx < lines.count-1 {
self += sep
}
}
}
init(_ lines:String...){
self = ""
for (idx, item) in lines.enumerated() {
self += "\(item)"
if idx < lines.count-1 {
self += "\n"
}
}
}
}
print(
String(
"Hello",
"World!"
)
)
"Hello
World!"
print(
String(sep:", ",
"Hello",
"World!"
)
)
"Hello, World!"
Run Code Online (Sandbox Code Playgroud)
And*_*ent 27
这是我注意到的关于Swift的第一个令人失望的事情.几乎所有脚本语言都允许使用多行字符串.
C++ 11添加了原始字符串文字,允许您定义自己的终结符
C#的@literals用于多行字符串.
即使是普通的C和老式的C++和Objective-C也只需将多个文字放在一起就可以实现连接,因此引用会被折叠.当你这样做时,空白不计算,所以你可以把它们放在不同的行上(但需要添加你自己的换行符):
const char* text = "This is some text\n"
"over multiple lines";
Run Code Online (Sandbox Code Playgroud)
由于swift不知道你已将文本放在多行上,我必须修复connor的样本,类似于我的C样本,明确说明换行符:
var text:String = "This is some text \n" +
"over multiple lines"
Run Code Online (Sandbox Code Playgroud)
小智 16
正如+litso 指出的那样,在一个表达式中重复使用-Operator会导致XCode Beta挂起(仅使用XCode 6 Beta 5进行检查):Xcode 6 Beta无法编译
现在,多行字符串的替代方法是使用字符串数组,reduce它具有+:
var text = ["This is some text ",
"over multiple lines"].reduce("", +)
Run Code Online (Sandbox Code Playgroud)
或者,可以说更简单,使用join:
var text = "".join(["This is some text ",
"over multiple lines"])
Run Code Online (Sandbox Code Playgroud)
Two*_*aws 15
从Swift 4.0开始,可以使用多行字符串,但是有一些规则:
"""."""也应该从它自己的行开始.除此之外,你很高兴!这是一个例子:
let longString = """
When you write a string that spans multiple
lines make sure you start its content on a
line all of its own, and end it with three
quotes also on a line of their own.
Multi-line strings also let you write "quote marks"
freely inside your strings, which is great!
"""
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅Swift 4中的新增功能.
Swift 4通过提供多行字符串文字支持解决了这个问题.要开始字符串文字添加三个双引号(""")并按回车键,按下返回键后开始用任何变量,换行符和双引号写字符串就像你会用记事本或任何文本编辑器写的那样.要结束多行字符串文字再次在新行中写入(""").
见下例
let multiLineStringLiteral = """
This is one of the best feature add in Swift 4
It let’s you write “Double Quotes” without any escaping
and new lines without need of “\n”
"""
print(multiLineStringLiteral)
Run Code Online (Sandbox Code Playgroud)
迅速:
@connor是正确的答案,但是如果你想在print语句中添加你正在寻找的行\n和/或\r,这些被称为Escape Sequences或Escaped Characters,这是关于该主题的Apple文档的链接..
例:
print("First line\nSecond Line\rThirdLine...")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
123950 次 |
| 最近记录: |