试图弄清楚如何使用Swift将字符串分成两半。基本上给了一个字符串"今天我在莫斯科,明天我将在纽约" 这个字符串有13个单词。我想生成2"接近长度"字符串:"今天我在莫斯科,明天"和明天我将在纽约"
答案 0 :(得分:4)
将单词分成数组,然后取两半:
let str = "Today I am in Moscow and tomorrow I will be in New York"
let words = str.componentsSeparatedByString(" ")
let halfLength = words.count / 2
let firstHalf = words[0..<halfLength].joinWithSeparator(" ")
let secondHalf = words[halfLength..<words.count].joinWithSeparator(" ")
print(firstHalf)
print(secondHalf)
根据您的喜好调整halfLength
。
答案 1 :(得分:0)
如果有人还在寻找简单的方法
在Swift 4及更高版本中:您只需在字符串中间插入
chara
,然后执行split(separator:
var str = "Hello, playground"
let halfLength = str.count / 2
let index = str.index(str.startIndex, offsetBy: halfLength)
str.insert("-", at: index)
let result = str.split(separator: "-")
有关String.Index的更多信息:Find it here
答案 2 :(得分:0)
我已经在一个有用的扩展程序中转换了很好的Code Different答案:
extension String {
func splitStringInHalf()->(firstHalf:String,secondHalf:String) {
let words = self.components(separatedBy: " ")
let halfLength = words.count / 2
let firstHalf = words[0..<halfLength].joined(separator: " ")
let secondHalf = words[halfLength..<words.count].joined(separator: " ")
return (firstHalf:firstHalf,secondHalf:secondHalf)
}
}
用法:
let str = "Today I am in Moscow and tomorrow I will be in New York".splitStringInHalf()
print(str.firstHalf)
print(str.secondHalf)