获取字符串上的字符位置

时间:2017-07-14 10:15:03

标签: ios swift swift3

我正在尝试在字符串中找到字符的当前位置。

角色本身是换行符\n

到目前为止,我已设法检测字符串是否包含具有以下代码的特定字符:

let till: Character = "\n"
if let idx = text.characters.index(of: till) {
    print("linefeed detected")
} else {
    print("not found")
}

如果我print idx变量,我会得到以下输出:

Index(_base: Swift.String.UnicodeScalarView.Index(_position: 35), _countUTF16: 1)

如您所见,如果给出位置,在这种情况下为35

我的问题是,如何访问该位置实例编号? 我怎么知道位置是X,Y还是Z.

谢谢。

3 个答案:

答案 0 :(得分:3)

你应该试试这个:

Swift 3

let till: Character = "\n"
    if let idx = text.characters.index(of: till)
    {
        let pos = text.characters.distance(from: text.startIndex, to: idx)
        print(pos)
    }
    else
    {
        print("not found")
    }

答案 1 :(得分:1)

您可以使用distance方法获取您要查找的字符索引。

extension String {
    func indexOf(string: String) -> Int? {
        if let indexOfCharacter = characters.index(of: Character(string)) {
            let distance = characters.distance(from: startIndex, to: indexOfCharacter)
            return distance
        }
        return nil
    }
}

答案 2 :(得分:-1)

//我希望它会帮助你

let NotFound = -1

extension String {
public func index(of charecter: Character) -> Int {
    if let index = characters.index(of: charecter) {
        return characters.distance(from: startIndex, to: index)
    }
    return NotFound
 }
}