如何将此字符串转换为忽略前2个字符和换行符(\ n)或空格的字符数组? 所以我有这个:
var leds = """
1 1
XXX
000
00X
"""
将其退还给我:
['x','x','x','0','0','0','0','0','x']
我有这个,但它不会忽略空格,换行符或第一行的编号:
let characters = Array(leds)
print(characters)
非常感谢您
答案 0 :(得分:5)
将字符串拆分为行数组,然后放置第一行。然后使用flatMap
将每一行映射到一个字符数组并连接结果。
let array = leds.components(separatedBy: .newlines)
.dropFirst()
.flatMap(Array.init)
print(array) // ["X", "X", "X", "0", "0", "0", "0", "0", "X"]
使用map
代替flatMap
,您将获得一个与输入字符串中的行和列相对应的“嵌套数组”:
let board = leds.components(separatedBy: .newlines)
.dropFirst()
.map(Array.init)
print(board) // [["X", "X", "X"], ["0", "0", "0"], ["0", "0", "X"]]
答案 1 :(得分:0)
这也可能有用-
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))
}