0

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"]

4 Answers 4

2

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)
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

'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"]

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.