Splitting A String Of Letters Into 3s In Swift
Swift newbie here. I am trying to convert some of my python code to swift and im stuck at the point where I need to split a string of letters into and array with each item being 3
Solution 1:
An easy and Swifty way to do this is to map an array of chars using the stride
and advance
functions:
let name =Array("ATAGASSTSSGASTA")
let splitName = map(stride(from: 0, to: name.count, by: 3)) {
String(name[$0..<advance($0, 3, name.count)])
}
Solution 2:
This is pretty verbose, but it does the job:
let name ="ATAGASSTSSGASTA"let array = reduce(name, [String]()) {
switch$0.last {
case .Some(let last) where countElements(last) <3:
var array =$0
array[array.endIndex-1].append($1)
return array
case .Some(_), .None:
return$0+ [String($1)]
}
}
Edit: In Swift 1.2, I think countElements
has changed to just count
. Not sure, don't have it yet, but the documents make it look that way.
Solution 3:
var nucString = "aatttatatatattgctgatctgatctEOS"let nucArrayChar = Array(nucString)
varnucArray: [String] = []
varcounter: Int = nucArrayChar.countif counter % 3 == 0 {
forvar startNo = 0; startNo < counter; startNo += 3 {
println("\(nucArray)\(startNo)")
nucArray.append(String(nucArrayChar[(startNo)...(startNo + 2)]))
}
}
Post a Comment for "Splitting A String Of Letters Into 3s In Swift"