代码之家  ›  专栏  ›  技术社区  ›  Zhou Haibo

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

  •  0
  • Zhou Haibo  · 技术社区  · 4 年前

    我今天已经进行了搜索,发现了类似的问题 here 但它并不能完全解决这个问题。在我的例子中,我想转换readLine输入字符串 "[3,-1,6,20,-5,15]" [3,-1,6,20,-5,15] .

    我正在做一个来自一个网站的在线编码任务,这需要从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($0))}
        print("nums: \(nums)")
    }
    
    0 回复  |  直到 4 年前
        1
  •  0
  •   Joakim Danielson    4 年前

    这里有一个将输入转换成整数数组的一行程序。当然,如果需要一些验证,您可能需要将其拆分为单独的步骤

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

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

    .replacingOccurrences(of: "[\\[\\]]", with: "", options: .regularExpression)
    
        2
  •  0
  •   AlexSmet    4 年前

    使用 split

    let nums = numsInput.split(separator: ",").compactMap {Int($0)}