参见英文答案 >
Finding index of character in Swift String2
我想将字符串中包含的字母的索引转换为整数值。尝试读取头文件,但是我找不到Index的类型,尽管它似乎符合使用方法(例如distanceTo)的ForwardIndexType协议。
我想将字符串中包含的字母的索引转换为整数值。尝试读取头文件,但是我找不到Index的类型,尽管它似乎符合使用方法(例如distanceTo)的ForwardIndexType协议。
var letters = "abcdefg" let index = letters.characters.indexOf("c")! // ERROR: Cannot invoke initializer for type 'Int' with an argument list of type '(String.CharacterView.Index)' let intValue = Int(index) // I want the integer value of the index (e.g. 2)
任何帮助是赞赏。
您需要使用与原始字符串起始索引相关的distanceTo(index)方法:
原文链接:https://www.f2er.com/swift/320330.htmllet intValue = letters.startIndex.distanceTo(index)
您还可以使用一种方法扩展字符串,以返回字符串中第一个出现的字符串,如下所示:
extension String { func indexDistanceOfFirst(character character: Character) -> Int? { guard let index = characters.indexOf(character) else { return nil } return startIndex.distanceTo(index) } } let letters = "abcdefg" let char: Character = "c" if let index = letters.indexDistanceOfFirst(character: char) { print("character \(char) was found at position #\(index)") // "character c was found at position #2\n" } else { print("character \(char) was not found") }
Xcode 8 beta 3•Swift 3
extension String { func indexDistance(of character: Character) -> Int? { guard let index = characters.index(of: character) else { return nil } return distance(from: startIndex,to: index) } } let letters = "abcdefg" let char: Character = "c" if let index = letters.indexDistance(of: char) { print("character \(char) was found at position #\(index)") // "character c was found at position #2\n" } else { print("character \(char) was not found") }