Swift 以 table 形式打印数组并添加特殊字符
Swift Printing an Array in a table form String and also adding special characters
假设我有这个字符串
var stringCSV = "Beth,Charles,Danielle,Adam,Eric\n17945,10091,10088,3907,10132\n2,12,13,48,11";
然后我将其转换为二维数组
[["Beth", "Charles", "Danielle", "Adam", "Eric"], ["17945", "10091", "10088", "3907", "10132"], ["2", "12", "13", "48", "11"]]
下面是我用来将字符串转换为二维数组并对其进行排序的代码。
struct Person {
let name: String
let id: String
let age: String
}
var csvFormatted = [[String]]()
stringCSV.enumerateLines { (line, _) in
var res = line.split(separator: ",",omittingEmptySubsequences: false).map{
String([=14=])
}
for i in 0 ..< res.count {
res[i] = res[i]
}
csvFormatted.append(res)
}
let properties = zip(csvFormatted[1],csvFormatted[2])
let namesAndProperties = zip(csvFormatted[0],properties)
let structArray = namesAndProperties.map { (name, properties) in
return Person(name: name, id: properties.0, age: properties.1)
}
let sortedArray = structArray.sorted {
return [=14=].name < .name
}
for i in sortedArray {
print(i.name, i.id, i.age)
}
我得到以下输出
Adam 3907 48
Beth 17945 2
Charles 10091 12
Danielle 10088 13
Eric 10132 11
但我不会理解并知道如何将排序后的数组打印回字符串,就像我将它拆分为一个数组并对其进行排序并包括特殊字符(如“\n”和“,”之前一样".
并取得以下成就
Adam,Beth,Charles,Danielle,Eric\n
3907,17945,10091,10088,10132\n
48,2,12,13,11
对每个 属性 使用 map
并将其加入以创建逗号分隔的行。然后使用数组中的结果再次用换行符连接。
let csv = [array.map(\.name).joined(separator: ","),
array.map(\.id).joined(separator: ","),
array.map(\.age).joined(separator: ",")]
.joined(separator: "\n")
假设我有这个字符串
var stringCSV = "Beth,Charles,Danielle,Adam,Eric\n17945,10091,10088,3907,10132\n2,12,13,48,11";
然后我将其转换为二维数组
[["Beth", "Charles", "Danielle", "Adam", "Eric"], ["17945", "10091", "10088", "3907", "10132"], ["2", "12", "13", "48", "11"]]
下面是我用来将字符串转换为二维数组并对其进行排序的代码。
struct Person {
let name: String
let id: String
let age: String
}
var csvFormatted = [[String]]()
stringCSV.enumerateLines { (line, _) in
var res = line.split(separator: ",",omittingEmptySubsequences: false).map{
String([=14=])
}
for i in 0 ..< res.count {
res[i] = res[i]
}
csvFormatted.append(res)
}
let properties = zip(csvFormatted[1],csvFormatted[2])
let namesAndProperties = zip(csvFormatted[0],properties)
let structArray = namesAndProperties.map { (name, properties) in
return Person(name: name, id: properties.0, age: properties.1)
}
let sortedArray = structArray.sorted {
return [=14=].name < .name
}
for i in sortedArray {
print(i.name, i.id, i.age)
}
我得到以下输出
Adam 3907 48
Beth 17945 2
Charles 10091 12
Danielle 10088 13
Eric 10132 11
但我不会理解并知道如何将排序后的数组打印回字符串,就像我将它拆分为一个数组并对其进行排序并包括特殊字符(如“\n”和“,”之前一样".
并取得以下成就
Adam,Beth,Charles,Danielle,Eric\n
3907,17945,10091,10088,10132\n
48,2,12,13,11
对每个 属性 使用 map
并将其加入以创建逗号分隔的行。然后使用数组中的结果再次用换行符连接。
let csv = [array.map(\.name).joined(separator: ","),
array.map(\.id).joined(separator: ","),
array.map(\.age).joined(separator: ",")]
.joined(separator: "\n")