我是swift的新手。希望解决这个难题......任何人都可以告诉我如何使用一个字符串的旧式indexOf参数传递给另一个字符串?
答案 0 :(得分:1)
您需要检查字符串的字符。像这样:
str.characters.indexOf("a")
这将返回角色的索引" a"在字符串中。
答案 1 :(得分:0)
第1部分:
hash
功能:
func hash(s: String) -> Int {
let letters = "acdegilmnoprstuw"
return (s.characters.startIndex..<s.characters.endIndex).reduce(7) { (h, currentIndex) -> Int in
let codeUnit = s.characters[currentIndex]
let startIndex = letters.characters.startIndex
let endIndex = letters.characters.indexOf(codeUnit)!
let index = startIndex.distanceTo(endIndex)
return h * 37 + index
}
}
let sevenLetter = hash("leepadg")
print(sevenLetter) // prints 680131659347
第2部分:
// based on https://blog.hjm.im/hashing-puzzle/
func reverseHash(hash: Int, allowedCharacters: [Character]) -> String {
var hash = hash
var indices = [Int: Int]()
var i = 0
while hash > 37 {
indices[i] = hash % 37
hash = hash / 37
i += 1
}
return (indices.count - 1).stride(through: 0, by: -1).reduce("") {
$0 + String(allowedCharacters[indices[$1]!])
}
}
let chars: [Character] = ["a", "c", "d", "e", "g", "i", "l", "m", "n", "o", "p", "r", "s", "t", "u", "w"]
print(reverseHash(680131659347, allowedCharacters: chars)) // prints "leepadg"
我将它作为练习留给读者用正确的哈希替换哈希:)