king yau
king yau

Reputation: 510

Swift 2 filter string to array

Is swift having any solution to search and splitting string to array?

For example,

let userList = "userid : 123, userName: Peter. userid :  321, userName : Joe. userid : 111, userName: Ken .userid :  222, userName : John"

To

let UserIdArray = ["123", "321", "111", "222"]
let UserNameArray = ["Peter", "Joe", "Ken", "John"]

Upvotes: 0

Views: 184

Answers (4)

user3441734
user3441734

Reputation: 17534

'pure' Swift solution

let userList = "userid : 123, userName: Peter. userid :  321, userName : Joe. userid : 111, userName: Ken .userid :  222, userName : John"

let arr = userList.characters.split { ",. :".characters.contains($0) }.map(String.init)
let arrf = arr.filter { $0 != "userid" && $0 != "userName" }

var userId:[String] = []
var userName:[String] = []

for (i,v) in arrf.enumerate() {
    if i % 2 == 0 {
        userId.append(v)
    } else {
        userName.append(v)
    }
}

print(userId, userName) // ["123", "321", "111", "222"] ["Peter", "Joe", "Ken", "John"]

Upvotes: 1

Shardul
Shardul

Reputation: 4274

Try this simple one.

let arr = userList.componentsSeparatedByString(",")

var arrA:[String] = []
var arrB:[String] = []

for str in arr {
    let tmp = str.componentsSeparatedByString(":")

    arrA.append(tmp[0])
    arrB.append(tmp[1])
}

print(arrA)
print(arrB)

But I liked the answer of @Dmitry

Upvotes: 0

vadian
vadian

Reputation: 285064

This is a solution using regular expression and capture groups

let userList = "userid : 123, userName: Peter. userid :  321, userName : Joe. userid : 111, userName: Ken .userid :  222, userName : John"
var userIdArray = [String]()
var userNameArray = [String]()

let pattern = "userid[:\\s]+(\\d+)[\\s,]+userName[:\\s]+(\\w+)"

do {
  let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions())
  let result = regex.matchesInString(userList, options: NSMatchingOptions(), range: NSRange(location: 0, length: userList.characters.count))
  let nsUserList = userList as NSString
  for item in result {
    userIdArray.append(nsUserList.substringWithRange(item.rangeAtIndex(1)))
    userNameArray.append(nsUserList.substringWithRange(item.rangeAtIndex(2)))
  }
  print(userIdArray, userNameArray)
} catch let error as NSError {
  print(error)
}

Upvotes: 2

Dmitry
Dmitry

Reputation: 2887

Regular expressions might help you with this.

Check out tutorial here - https://www.raywenderlich.com/86205/nsregularexpression-swift-tutorial

It will be like this: "userName\s*:\s*([^,\s]+)(,|.|$)"

And for userid just replace userName with userid.

Upvotes: 1

Related Questions