Search code examples
swiftreadline

Swift: how to convert readLine() input " [-5,20,8...] " to an Int array


I already run the search today and found a similar issue here, but it not fully fix the issue. In my case, I want to convert readLine input string "[3,-1,6,20,-5,15]" to an Int array [3,-1,6,20,-5,15].

I'm doing an online coding quest from one website, which requires input the test case from readLine().

For example, if I input [1,3,-5,7,22,6,85,2] in the console then I need to convert it to Int array type. After that I could deal with the algorithm part to solve the quest. Well, I think it is not wise to limit the input as readLine(), but simply could do nothing about that:(

My code as below, it could deal with positive array with only numbers smaller than 10. But for this array, [1, -3, 22, -6, 5,6,7,8,9] it will give nums as [1, 3, 2, 2, 6, 5, 6, 7, 8, 9], so how could I correctly convert the readLine() input?

print("please give the test array with S length")
if let numsInput = readLine() {
    let nums = numsInput.compactMap {Int(String($0))}
    print("nums: \(nums)")
}

Solution

  • Here is a one liner to convert the input into an array of integers. Of course you might want to split this up in separate steps if some validation is needed

    let numbers = input
        .trimmingCharacters(in: .whitespacesAndNewlines)
        .dropFirst()
        .dropLast()
        .split(separator: ",")
        .compactMap {Int($0)}
    

    dropFirst/dropLast can be replaced with a replace using a regular expression

    .replacingOccurrences(of: "[\\[\\]]", with: "", options: .regularExpression)