Split a String into an Array in Swift

Split a String into an array in Swift?

The Swift way is to use the global split function, like so:

var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}
var firstName: String = fullNameArr[0]
var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil

with Swift 2

In Swift 2 the use of split becomes a bit more complicated due to the introduction of the internal CharacterView type. This means that String no longer adopts the SequenceType or CollectionType protocols and you must instead use the .characters property to access a CharacterView type representation of a String instance. (Note: CharacterView does adopt SequenceType and CollectionType protocols).

let fullName = "First Last"
let fullNameArr = fullName.characters.split{$0 == " "}.map(String.init)
// or simply:
// let fullNameArr = fullName.characters.split{" "}.map(String.init)

fullNameArr[0] // First
fullNameArr[1] // Last

In Swift, can you split a string by another string, not just a character?

import Foundation

let inputString = "This123Is123A123Test"
let splits = inputString.components(separatedBy: "123")

Question on how to split a string into an array of desired strings in Swift

You can use reduce to iterate the string over each character and either append it to an array if it is an uppercase letter or add it to the last element of the array otherwise

let str = "F'2R'UU2"

let res = str.reduce(into: [String]()) {
if $1.isUppercase || $0.isEmpty {
$0.append("\($1)")
} else {
$0[$0.count - 1] = $0.last! + "\($1)"
}
}

Swift 3: Split string into Array of Int

Use this

let stringNumbers = "1 2 10"
let array = stringNumbers.components(separatedBy: " ")
let intArray = array.map { Int($0)!} // [1, 2, 10]

How to split a string into 2 arrays Swift 4

Try this and see: Use loop with if-let or if-is condition to identify data type of array element and append into relevant array.

Here is test example:

let array = ["Hello", "World ", "1" , "2"]

var arrayStr = [String]()
var arrayInt = [Int]()


for arrayElement in array {

if let intValue = Int(arrayElement) {
arrayInt.append(intValue)
} else {
arrayStr.append(arrayElement)
}
}

print("arrayStr - \(arrayStr)")
print("arrayInt - \(arrayInt)")

Result:

arrayStr - ["Hello", "World"]

arrayInt - [1, 2]

Sample Image

How to split string into array of words, and also get their ranges?

You can use enumerate substrings in range and pass byWords options:

extension StringProtocol {
var wordsAndRanges: [(word: String,range: Range<Index>)] {
var result: [(word: String, range: Range<Index>)] = []
enumerateSubstrings(in: startIndex..., options: .byWords) { word, range, _, _ in
guard let word = word else { return }
result.append((word, range))
}
return result
}
}


let string = "This is a string."
for (word, range) in string.wordsAndRanges {
print("word:", word)
print("substring:", string[range])
print("range:", range)
}

Or using a Word struct as you tried:

struct Word {
let range: Range<String.Index>
let component: String
}


extension StringProtocol {
var words: [Word] {
var result: [Word] = []
enumerateSubstrings(in: startIndex..., options: .byWords) { word, range, _, _ in
guard let word = word else { return }
result.append(.init(range: range, component: word))
}
return result
}
}


let string = "This is a string."
for word in string.words {
print("word:", word.component)
print("subsequence", string[word.range])
print("range", word.range)
}

Split String into Array keeping delimiter/separator in Swift

Suppose you are splitting the string by a separator called separator, you can do the following:

let result = yourString.components(separatedBy:  separator) // first split
.flatMap { [$0, separator] } // add the separator after each split
.dropLast() // remove the last separator added
.filter { $0 != "" } // remove empty strings

For example:

let result = " Hello World ".components(separatedBy:  " ").flatMap { [$0, " "] }.dropLast().filter { $0 != "" }
print(result) // [" ", "Hello", " ", "World", " "]


Related Topics



Leave a reply



Submit