Swift - 在字符串中的多个位置查找字符

时间:2015-07-11 16:03:50

标签: string swift

在Swift中,使用以下字符串:"这是一个字符串",如何获取字符"的索引数组。 " (空格)出现在字符串中?

期望的结果:[4,7,9]

我试过了:

func SetLayoutAccordingToDesiredLayout(DesiredLayout : enum_Layout){
     if DesiredLayout == self.Current_Layout && IsSetPosition == true {
        return
     }
     self.IsSetPosition = false
     self.Current_Layout = DesiredLayout
     if DesiredLayout == enum_Layout.OneColumn || DesiredLayout == enum_Layout.TwoColumn {
     DoColumnLayout()
     }else{
     DoRecordLayout()
     }
 }
func DoRecordLayout(){
    let dFrame = self.contentView.frame
    self.Thumbnail.frame = CGRect(x: 0, y: 0, width: dFrame.height, height: dFrame.height)
    ...
 }
func DoColumnLayout(){
    let dFrame = self.contentView.frame
    self.Thumbnail.frame = CGRect(x: 0, y: 0, width: dFrame.width, height: dFrame.width)
    ...
}
override func applyLayoutAttributes(layoutAttributes: UICollectionViewLayoutAttributes!) {
    self.layoutIfNeeded()
    self.SetLayoutAccordingToDesiredLayout(self.Current_Layout)

}
override func willTransitionFromLayout(oldLayout: UICollectionViewLayout, toLayout newLayout: UICollectionViewLayout) {
    let nLayout = newLayout as! ProductCollectionViewLayout
    let enumLayout = nLayout._enumLayout
    self.Current_Layout = enumLayout
}

但这只会返回4,而不是所有索引。

有什么想法吗?

2 个答案:

答案 0 :(得分:7)

这是一个简单的方法:

let string = "this is a string"

let indices = string
    .characters
    .enumerate()
    .filter { $0.element == " " }
    .map { $0.index }

print(indices) // [4, 7, 9]
  • characters返回CharacterViewCollectionType(类似于单个字符数组)
  • enumerate将此集合转换为SequenceType元组,其中包含index(0到15)和element(每个角色)
  • filter删除字符不是空格的元组
  • map将元组数组转换为仅包含索引的数组

这种方法需要Swift 2(在Xcode 7 beta中)。从评论中,Swift 1.2语法:

let indices = map(filter(enumerate(string), { $0.element == " " }), { $0.index } )

(帽子提示Martin R)。

答案 1 :(得分:0)

使用Regex的Swift 1.2解决方案

func searchPattern(pattern : String, inString string : String) -> [Int]?
{
  let regex = NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions(), error: nil)
  return regex?.matchesInString(string, options: NSMatchingOptions(), range: NSRange(location:0, length:count(string)))
               .map { ($0 as! NSTextCheckingResult).range.location }
}

let string = "this is a string"

searchPattern("\\s\\S", inString : string) // [4, 7, 9]
searchPattern("i", inString : string) // [2, 5, 13]