Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Swift 2中搜索字符串_Swift_Swift2 - Fatal编程技术网

如何在Swift 2中搜索字符串

如何在Swift 2中搜索字符串,swift,swift2,Swift,Swift2,我是斯威夫特的新手。希望解决这个难题。。。有人能告诉我如何使用一个字符串的老式indexOf参数传递到另一个字符串吗 您需要检查字符串的字符。像这样: str.characters.indexOf("a") 这将返回字符串中字符“a”的索引。第1部分: hash函数: func hash(s: String) -> Int { let letters = "acdegilmnoprstuw" return (s.characters.startIndex..<s.chara

我是斯威夫特的新手。希望解决这个难题。。。有人能告诉我如何使用一个字符串的老式indexOf参数传递到另一个字符串吗


您需要检查字符串的字符。像这样:

str.characters.indexOf("a")
这将返回字符串中字符“a”的索引。

第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
我将把它作为一个练习留给读者,让他们用正确的哈希替换:)

“问题本身”的意思是作为文本,以便可以对其进行索引和搜索,而不是作为图片。
// 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"