string - How to compare each letters in an array with all the letters in another array? - Swift -
i have 2 different arrays called: criptedchar , alphabet. need check first character in criptedchar (so "criptedchar[0]) , check correspondence in alphabet. exemple: criptedchar // ["d","e","c","b"] alphabet // ["a","b","c" , on] want take d criptedchar[0] , check if there's "d" in alphabet , save position of "d" in second array. need increment number inside parenthesis of criptedchar. i'll take number user. can please me? thank you!
func decript() { var criptedtext = incriptedtext.text! //get text uitextfield var criptedchar = array<character>(criptedtext.characters) //from text char & in array :d var alfabeto: array<character> = ["a","b", "c", "d", "e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] var capacitycriptedchararray = criptedchar.capacity (var = 0; < 26; i++) { if criptedchar[0] == alfabeto[i] { decriptedtext.text = decriptedtext.text! + "\(newlettersfromsecondviewcontroller[i])" } } (var = 0; < 26; i++) { if criptedchar[1] == alfabeto[i] { decriptedtext.text = decriptedtext.text! + "\(newlettersfromsecondviewcontroller[i])" } } (var = 0; < 26; i++) { if criptedchar[2] == alfabeto[i] { decriptedtext.text = decriptedtext.text! + "\(newlettersfromsecondviewcontroller[i])" } } }
this code works, it's dumb , have no control of user input
if understand question correctly, looking (explanations inline):
// start crypted text, , empty string result: let cryptedtext = "mifpyx" var decryptedtext = "" // 2 character arrays (of equal length): let alphabet = array("abcdefghijklmnopqrstuvwxyz".characters) let newletters = array("ghijklmnopqrstuvwxyzabcdef".characters) // each character in input string: c in cryptedtext.characters { // check if `c` contained in `alphabet` array: if let index = alphabet.indexof(c) { // yes, is, @ position `index`! // append corresponding character second array result: decryptedtext.append(newletters[index]) } } print(decryptedtext) // solved
alternatively, can create lookup-dictionary 2 arrays:
var mapping = [ character : character ]() zip(alphabet, newletters).foreach { mapping[$0] = $1 }
and map each character input through dictionary:
let decryptedtext = array(cryptedtext.characters .map { mapping[$0] } .flatmap { $0 } )
(here flatmap
used filter-out nil
s characters not present in input array.)
Comments
Post a Comment