ios - 将字符串转换为 Int 数组

标签 ios arrays string swift int

例如,我有这种类型的字符串:

var test:String = "[1, 0, 4]";

我需要将它转换为 Int 数组:

var testConverted:[Int] = [ 1, 0, 4 ];

最佳答案

您需要使用 stringByTrimmingCharactersInSet 修剪开始和结束括号,然后使用 componentsSeparatedByString 获取字符串元素数组。然后您最终可以使用 flatMap 从中创建一个整数数组。

例如:

let yourString = "[1, 0, 4]"

// trim off the start and end brackets of the string – then obtain an array of elements by using componentsSeparatedByString
let arrayOfStrings = yourString.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "[]")).componentsSeparatedByString(", ")

// flatMap the arrayOfStrings to an array of integers, filtering out any strings that cannot be represented as numbers
let arrayOfInts = arrayOfStrings.flatMap{Int($0)}
print(arrayOfInts)

关于ios - 将字符串转换为 Int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36765670/

相关文章:

javascript - 在javascript中将复选框的属性值插入数组

ios - 为企业 iOS 应用制作安装链接

ios - 计算 UITableViewCell 的最佳图像大小

ios - 在 Swift 中按下回车键时退出键盘

java - 通过空指针中途终止 char[] -> String 转换

c# - C#中如何删除所有带括号的字符串?

asp.net - 删除 SQL 更新中 WHERE 之前的最后一个逗号

objective-c - 哪些问题可能导致将 nib 文件的所有者设置为 nil?

c# - 如何编码 Int 数组或指向 Int 数组的指针

php - "Indirect modification of overloaded element of SplFixedArray has no effect"