0

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)")
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
Zhou Haibo
  • 1,681
  • 1
  • 12
  • 32
  • I think we want to check it while input then you need do write readLine() fun inside while loop can when use insert any value check if is valid or not, if it valid then save it in your array, run that while loop until you will not get proper input values with count. – Pravin Tate Feb 23 '20 at 14:44

2 Answers2

1

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)
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
  • Thanks you, I make this post as answer, because it solves my question as well as provide other options for dealing with the input String. – Zhou Haibo Feb 24 '20 at 10:14
0

Use split method to get a sequence of strings from an input string

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

AlexSmet
  • 2,141
  • 1
  • 13
  • 18