我怎么能在多行分割字符串,如下面?
var text:String = "This is some text
over multiple lines"
我怎么能在多行分割字符串,如下面?
var text:String = "This is some text
over multiple lines"
当前回答
这是我注意到的斯威夫特的第一件令人失望的事情。几乎所有脚本语言都允许多行字符串。
c++ 11添加了原始字符串字面值,允许您定义自己的终止符
c#有它的@literals用于多行字符串。
即使是普通的C以及老式的c++和Objective-C也允许通过将多个文字相邻放置来进行连接,因此引号被折叠。当你这样做的时候,空格不算数,所以你可以把它们放在不同的行上(但需要添加你自己的换行符):
const char* text = "This is some text\n"
"over multiple lines";
由于swift不知道你已经把你的文本超过多行,我必须修复connor的样本,类似于我的C样本,显式地声明换行:
var text:String = "This is some text \n" +
"over multiple lines"
其他回答
迅速:
@connor是正确答案,但如果你想在打印语句中添加行,你要寻找的是\n和/或\r,这些被称为转义序列或转义字符,这是一个关于该主题的Apple文档链接。
例子:
print("First line\nSecond Line\rThirdLine...")
你可以使用unicode equals for enter或\n并在你的字符串中实现它们。例如:\u{0085}。
下面是一个代码片段,用n个字符分隔字符串:
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
override func loadView() {
let str = String(charsPerLine: 5, "Hello World!")
print(str) // "Hello\n Worl\nd!\n"
}
}
extension String {
init(charsPerLine:Int, _ str:String){
self = ""
var idx = 0
for char in str {
self += "\(char)"
idx = idx + 1
if idx == charsPerLine {
self += "\n"
idx = 0
}
}
}
}
一种方法是将标签文本设置为attributedText,并更新字符串变量以包含换行符的HTML (<br />)。
例如:
var text:String = "This is some text<br />over multiple lines"
label.attributedText = text
输出:
This is some text
over multiple lines
希望这能有所帮助!
我在String上使用了一个扩展来实现多行字符串,同时避免编译器挂起的错误。它还允许您指定分隔符,以便您可以像使用Python的join函数一样使用它
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!"