2016-06-29 4 views
1

Swiftを使用して文字列を半分に分割する方法を理解しようとしています。基本的に文字列「今日はモスクワにあり、明日はニューヨークに行く」 この文字列は13語です。私は2つの「長さが近い」文字列を生成したいと思います:「今日はモスクワと明日に」そして「明日はニューヨークにいます」Swiftで半分の文字列を分割する(Word-Aware)

答えて

3

単語を分割して2つの半分:

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を好きなように調整します。