arrays - 转换字符串?

标签 arrays swift string type-conversion

我有一个这样的字符串:

let arrayString : String = "[[1, 123, 0], [4, 003, 21]]"

我想将此字符串转换为以下类型的二维数组:[[String]]

<小时/>

我尝试使用类似这样的行:

var array : [[String]]  = arrayString as! [[String]]; // abort error

还有类似这样的东西:

if let json = try? JSONSerialization.jsonObject(with: ucode.data(using: .utf8)!, options: []) {
        let array = json as! [[String]];
        print(array[0][0]) // prints nothing --> just ""
    }
<小时/>

So I got no idea how I could solve this problem to convert:

"[[1, 123, 0], [4, 003, 21]]" ----> [["1", "123", "0"], ["4", "003", "21"]]

任何帮助将不胜感激,提前一百万致谢。

最佳答案

基本上这个字符串是 JSON,但序列化程序提示前导零。

解决方案是在反序列化 JSON 之前添加双引号,将整数值转换为 String。这可以通过正则表达式简单地实现

let arrayString = "[[1, 123, 0], [4, 003, 21]]"
let convertedArrayString = arrayString.replacingOccurrences(of: "\\d+", with: "\"$0\"", options: .regularExpression)
let data = Data(convertedArrayString.utf8)
do {
    if let array = try JSONSerialization.jsonObject(with: data) as? [[String]] {
        print(array)
    }
} catch { print(error)}

关于arrays - 转换字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49840088/

相关文章:

java - 在 Java 中,为什么 Array 的类构造函数是私有(private)的?

ios - 如何从设备获取 PDF 文件以便能够从我的应用程序上传它?

python - PyOpenCL 在内核代码中索引 3D 数组

javascript - 选择一个日期,然后将格式从 UNIX 转换为 UTC(yyyymmdd)

ios - 单击按钮会隐藏键盘,并且键盘弹起时不会执行操作

ios - cell.layoutifneeded 和 cell.layoutSubviews 以及 cell.setneedsdisplay 方法一般做什么?

c# - 如何获取此字符串中标签的 href 属性?

c# - 在最后一次出现模式 C# 后提取所有字符

Python:从字符串元组中获取第一个元素

php - 如何合并具有不同键数的两个数组的第二级值?