在子字符串中查找字符的位置

时间:2016-04-10 16:44:53

标签: string swift

如何在子字符串中找到字符的第一个位置。不是整个字符串,而是指定字符位置后的第一个。

示例:

var str = "This is a test string"
//find the position of first "i" after "is"

let position = str.firstPositionOfIAfterPosition(5) // returns 18

我知道我可以通过下面的代码找到整体的第一个位置。如何将其扩展为仅在指定的字符位置后开始查看?

   let position = str.rangeOfString("i").startIndex

3 个答案:

答案 0 :(得分:1)

var str = "This is a test string"


func getIndexAfterString(string: String) -> Int {
    let firstIndex = str.rangeOfString(string)?.startIndex.advancedBy(string.characters.count)
    let i: Int = str.startIndex.distanceTo(firstIndex!)
    let secondIndex = str.substringFromIndex(firstIndex!).rangeOfString("i")?.startIndex
    let j: Int = str.startIndex.distanceTo(secondIndex!)
    return i + j
}

let index: Int = getIndexAfterString(" is ") //18

答案 1 :(得分:1)

from tkinter.constants import *

答案 2 :(得分:1)

类似于matt的答案,但是String扩展和错误处理

extension String {

  func firstPositionOf(string: String, afterPosition index: Int) -> String.Index?
  {
    if self.isEmpty || self.characters.count - 1 < index { return nil }
    let subRange = Range<String.Index>(self.startIndex.advancedBy(index + 1)..<self.endIndex)
    guard let foundRange = self.rangeOfString(string, options: [], range: subRange) else { return nil }
    return foundRange.startIndex
  }
}

let str = "This is a test string"

let position = str.firstPositionOf("i", afterPosition:5) // -> 18