1

how do I convert this string to an array of characters ignoring the first 2 characters and line breaks (\n) or spaces ? so I do have this:

var leds = """
1 1
XXX
000
00X
"""

to return this to me as a result:

['x','x','x','0','0','0','0','0','x']

I have this, but it doesn't ignore the spaces, line breaks or the number of the first line:

let characters = Array(leds)
print(characters)

thank you very much in advance

2 Answers 2

5

Split the string into an array of lines, and drop the first line. Then use flatMap to map each line to an array of characters and concatenate the result.

let array = leds.components(separatedBy: .newlines)
    .dropFirst()
    .flatMap(Array.init)

print(array) // ["X", "X", "X", "0", "0", "0", "0", "0", "X"]

With map instead of flatMap you would get a “nested array” corresponding to the rows and columns from the input string:

let board = leds.components(separatedBy: .newlines)
    .dropFirst()
    .map(Array.init)

print(board) // [["X", "X", "X"], ["0", "0", "0"], ["0", "0", "X"]]
Sign up to request clarification or add additional context in comments.

Comments

0

This could also be useful-

if let firstLine = leds.components(separatedBy: CharacterSet.newlines).first {
        let removeFirstLineStr = leds.replacingOccurrences(of: firstLine, with: "")
        let characters = String(removeFirstLineStr.filter { !" \n\t\r".contains($0) })
        print(Array(characters))
    }

OR

func getCharacters() {
    guard let firstLineStr = leds.components(separatedBy: "\n").first else {
        return
    }
    let removeFirstLineStr = leds.replacingOccurrences(of: firstLineStr, with: "")
    let characters = String(removeFirstLineStr.filter { !" \n\t\r".contains($0) })
    print(Array(characters))
}

1 Comment

MUCHAS GRACIAS FUNCIONA

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.