問題描述
在 SWIFT 中遇到逗號時將字符串換行 (Break string to newline when meeting a comma in SWIFT)
我正在從 Web 服務接收字符串。我將我的標籤文本設置為該字符串的文本。但是,字符串包含逗號,我想將字符串分隔為新行,用逗號分隔。
示例:
var exampleString = "street Number, City"
需要為
var wantedString = "street Number
City"
這就是我當前設置標籤文本的方式:
self.AdresseLabel.text = self.SpillestedAdresse as String
任何想法如何拆分字符串?
謝謝!
參考解法
方法 1:
You don't need anything fancy, just replace comma with new lines:
let wantedString = exampleString.stringByReplacingOccurrencesOfString(", ", withString: "\n")
方法 2:
If your intention is to replace a comma (followed by zero, one or more space characters) by a newline character, then a string replacement with a regular expression pattern is an option:
let exampleString = "street Number, City"
let wantedString = exampleString.stringByReplacingOccurrencesOfString(",\\s*",
withString: "\n",
options: .RegularExpressionSearch)
print(wantedString)
Output:
street Number City
(by Goomey、Code Different、Martin R)