Trying to figure out how to split a string in half using Swift. Basically given a string "Today I am in Moscow and tomorrow I will be in New York" This string has 13 words. I would like to generate 2 "close in length" strings: "Today I am in Moscow and tomorrow" and "tomorrow I will be in New York"
            Asked
            
        
        
            Active
            
        
            Viewed 3,481 times
        
    3 Answers
8
            Break the words into an array, then take the two halves of it:
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)
Adjust halfLength to your likings.
 
    
    
        Code Different
        
- 90,614
- 16
- 144
- 163
1
            
            
        If anyone still looking for a simple way
In Swift 4 and above: you can just insert a
charain the middle of the string and then do asplit(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: "-")
for more info about String.Index: Find it here
 
    
    
        Siempay
        
- 876
- 1
- 11
- 32
1
            
            
        Swift 5.0
I've converted the good Code Different answer's in a useful extension:
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)
    }
}
Usage:
let str = "Today I am in Moscow and tomorrow I will be in New York".splitStringInHalf()
print(str.firstHalf)
print(str.secondHalf)
 
    
    
        Alessandro Ornano
        
- 34,887
- 11
- 106
- 133
