如何拆分字符串以包含分隔符?
假设我有一个像......这样的字符串。
let myString = "apple banana orange grapes"
如果我用过
let separatedString = myString.componentsSeparatedByString(" ")
我的结果数组将是
["apple","banana","orange","grapes"]
我将如何实现
的结果["apple ","banana ","orange ","grapes"]
答案 0 :(得分:1)
array.map
可让您处理生成的数组并重新添加空格。
let separatedString = myString
.componentsSeparatedByString(" ")
.map { "\($0) " }
最后一行迭代拆分数组中的所有字符串并将它们放在$0
中,并返回一个新的字符串,其中添加了一个空格,用作原始字符串的替换。
答案 1 :(得分:1)
由于您更新了问题,现在看起来您不再需要在最后一个单词上添加新空格。
所以这是我的更新代码
let text = "apple banana orange grapes"
let chunks: [String] = text
.componentsSeparatedByString(" ")
.reverse()
.enumerate()
.map { $0.element + ( $0.index == 0 ? "" : " ") }
.reverse()
print(chunks) // ["apple ", "banana ", "orange ", "grapes"]
感谢 @vadian 提出建议
let text = "apple banana\norange grapes"
let chunks: [String] = text
.componentsSeparatedByCharactersInSet(.whitespaceAndNewlineCharacterSet())
.reverse()
.enumerate()
.map { $0.element + ( $0.index == 0 ? "" : " ") }
.reverse()
print(chunks) // ["apple ", "banana ", "orange ", "grapes"]
答案 2 :(得分:1)
使用正则表达式的替代方法:
let myString = "apple banana orange grapes"
let pattern = "\\w+\\s?"
let regex = try! NSRegularExpression(pattern: pattern, options: [])
let matches = regex.matchesInString(myString, options:[], range: NSMakeRange(0, myString.characters.count))
.map { (myString as NSString).substringWithRange($0.range)}
print(matches) // -> ["apple ", "banana ", "orange ", "grapes"]