用括号分割Swift中的字符串

时间:2015-08-20 09:51:18

标签: macos swift

我将以下数据作为字符串获取。现在我想解析那个字符串。

{{"1", "test.pdf", 495207}, {"2", "test2.ics", 972}}`

我想先将String分成

{"1", "test.pdf", 495207}
{"2", "test2.ics", 972}

然后我会有一个我会像这样实习的课程

test(1, "test.pdf", 495207)
test(2, "test2.ics", 972)

如何使用Swift执行此操作? Split是一种可能的解决方案。如果我选择,它会分裂多次。

更新

我不太精确。我的结果不应该是每个括号的字符串。我想访问值1test.pdf等,并将它们保存到变量中以便进一步处理。

3 个答案:

答案 0 :(得分:3)

如果用方括号“{}”替换源字符串括号“[]”,则源成为一个有2个元素的有效Json数组,每个元素都是一个包含3个值的数组 - 比你大可以使用NSJSONSerialization解析它:

var source = "{{\"1\", \"test.pdf\", 495207}, {\"2\", \"test2.ics\", 972}}"
var string = source.stringByReplacingOccurrencesOfString("{", withString: "[")
string = string.stringByReplacingOccurrencesOfString("}", withString: "]")

let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
let json = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.allZeros, error: nil) as? [AnyObject]

var objects: [MyClass] = []

if let array = json {
    for element in array {
        let array    = element as! [AnyObject]
        let id       = array[0] as! String
        let filename = array[1] as! String
        let number   = array[2] as! UInt
        objects.append(MyClass(id: id, filename: filename, number: number))
    }
}

答案 1 :(得分:1)

可能的解决方案是 -

    var str = "{{\"1\", \"EX9OEH.pdf\", 495207}, {\"2\", \"BAHN_Fahrplan_20150814.ics\", 972}}"

    struct Item
    {
      var first : String
      var second : String
      var third : String
    }


    //First get the contents as a string by stripping opening and closing braces
    //Range-
    let range  = Range(start: (advance(str.startIndex, 1)),
      end: advance(str.endIndex, -1))

    //Strip all quotes

    str = str.stringByReplacingOccurrencesOfString("\"", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
    //Strip all braces
    str = str.stringByReplacingOccurrencesOfString("{", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
    str = str.stringByReplacingOccurrencesOfString("}", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)


    //Get the components seperated by comma

    var components = str.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: ","))

 //Build the item objects-
    var items:[Item]  = []

    var i:Int = 0

    while (i < components.count){
      //Extract 3 components per item
       var item = Item(first: components[ i ], second: components[ i + 1], third: components[i + 2])
      i += 3
      items.append(item)

    }

答案 2 :(得分:0)

您只需按正确的顺序替换字符:

text.stringByReplacingOccurrencesOfString("{{", withString: "{")

    text.stringByReplacingOccurrencesOfString("}}", withString: "}")

    text.stringByReplacingOccurrencesOfString("{", withString: "(")

    text.stringByReplacingOccurrencesOfString("}", withString: ")")