Swift:如何将 readLine() 输入“[-5,20,8...]”转换为 Int 数组

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

我今天已经 运行 搜索并发现了类似的问题 ,但它并没有完全解决问题。就我而言,我想将 readLine 输入字符串 "[3,-1,6,20,-5,15]" 转换为 Int 数组 [3,-1,6,20,-5,15].

我正在从一个网站进行在线编码任务,这需要从 readLine() 输入测试用例。

比如我在控制台输入[1,3,-5,7,22,6,85,2],那么我需要将它转换成Int数组类型。之后我可以处理算法部分来解决任务。好吧,我认为将输入限制为 readLine() 是不明智的,但对此无能为力:(

我的代码如下,它可以处理只有小于 10 的数字的正数组。但是对于这个数组,[1, -3, 22, -6, 5,6,7,8,9] 它将 nums 作为 [1, 3, 2, 2, 6, 5, 6, 7, 8, 9],那么我怎样才能正确转换 readLine() 输入?

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

使用 split 方法从输入字符串中获取字符串序列

let nums = numsInput.split(separator: ",").compactMap {Int([=11=])}

这是将输入转换为整数数组的单行代码。当然,如果需要一些验证,您可能希望将其分成不同的步骤

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

dropFirst/dropLast可以用正则表达式替换

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