在Swift中分隔一个字符串

时间:2017-07-25 02:42:24

标签: swift string substring

如何获取冒号后的值?

示例字符串:“aaa:test,bbb:test,ccc:test”

我必须识别 aaa: bbb: ccc:以获取冒号后的值。

还有一个特例:“aaa:aaa:,bbb:bbb ,, ccc:test”

该值可能与变量具有完全相同的单词,也可能没有。此外,该值可能包含逗号。

1 个答案:

答案 0 :(得分:2)

使用String的componentsnetSeparatedBy方法。我假设所有的键值都将由" ,"

   let wordsArr = "aaa:test: , bbb:test,a , ccc:test".components(separatedBy: " , ") as [String]

这会给你一个单词{[aaa:test:],[bbb:test,a],[ccc:test]}

    var aaa, bbb, ccc : String?


    for (_,keyValueWords) in wordsArr.enumerated()  {

        var strKeyValuePair = keyValueWords
        if strKeyValuePair.hasPrefix("aaa:") {
            aaa = String(strKeyValuePair.characters.dropFirst(4))
        }
        else if strKeyValuePair.hasPrefix("bbb:"){
            bbb = String(strKeyValuePair.characters.dropFirst(4))

        }else  if strKeyValuePair.hasPrefix("ccc:"){
            ccc = String(strKeyValuePair.characters.dropFirst(4))
        }

    }

    print("aaa=\(aaa!) , bbb=\(bbb!) , ccc=\(ccc!)")