4

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"

3 Answers3

6

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
  • 82,550
  • 14
  • 135
  • 153
1

If anyone still looking for a simple way

In Swift 4 and above: you can just insert a chara in the middle of the string and then do a 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: "-")

for more info about String.Index: Find it here

Siempay
  • 822
  • 1
  • 11
  • 28
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
  • 33,355
  • 11
  • 97
  • 127