将字符串转换为Int数组

时间:2016-04-21 09:40:38

标签: ios arrays string swift int

我是那种类型的String,例如:

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

我需要将其转换为Int:

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

2 个答案:

答案 0 :(得分:2)

您需要使用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)

答案 1 :(得分:1)

试试这个:

var test = "[1, 0, 4]"

test = test.substringToIndex(test.endIndex.advancedBy(-1)).substringFromIndex(test.startIndex.advancedBy(1))
var result = test.componentsSeparatedByString(", ").flatMap {Int($0)}
print(result) // [1, 0, 4]