componentsSeparatedByString在swift

时间:2016-04-01 06:49:06

标签: ios string swift

在我的一个应用程序中,有一个时间字符串,我需要将每个部分分开并处理它。

我的字符串就像

9:00 AM – 11:00 PM

9:00 AM – 11:00 PM,9:00 AM – 11:00 PM

Printing description of self.placeOpenTime:
"10:00 AM – 1:00 PM, 5:00 – 8:00 PM"
Printing description of allparts:
▿ 2 elements
  - [0] : "10:00 AM – 1:00 PM"
  - [1] : " 5:00 – 8:00 PM"

所以我分离字符串的代码是

let allparts = self.placeOpenTime.componentsSeparatedByString(",")

for (index,_) in allparts.enumerate() {

     let currentPart = allparts[index]

     let timeParts = currentPart.componentsSeparatedByString(" - ")
}

从此代码中我得到timePartscurrentPart

相同

currentPart =" 9:00 AM - 11:00 PM"

Printing description of timeParts:
▿ 1 elements
  - [0] : "9:00 AM – 11:00 PM" 

应该是

[0] : 9:00 AM
[1] : 11:00 PM

任何帮助将不胜感激。提前谢谢。

2 个答案:

答案 0 :(得分:1)

根据@wain评论,我检查了“ - ”的unicode值并且它有效。

我已经替换了这段代码

let currentPart : String = allparts[index]

let data = "\\U2013".dataUsingEncoding(NSUTF8StringEncoding)

let unicode = NSString(data: data!, encoding: NSNonLossyASCIIStringEncoding)

let timeParts = currentPart.componentsSeparatedByString(" \(unicode!) ")

哪个更复杂的代码做小事。因此,根据@Martin R的建议,执行此操作的简单代码是

let currentPart : String = allparts[index]

let timeParts = currentPart.componentsSeparatedByString(" \u{2013} ") 

答案 1 :(得分:0)

 //may be issue with separetor string , once check is the separtor is proper string or not
 let timeParts = currentPart.componentsSeparatedByString("-")