swift - 如何使用while循环遍历用户输入的单词以查找每个字母的索引
问题描述
我是快速编程的新手,并且正在努力使用我想要使用的简单方法。我在数组中添加了随机字母,我希望用户输入一个单词。然后,该方法应遍历该单词的每个字母并返回每个字母的索引,以便为该单词输出一个数字代码。例如。如果我输入“swift”,它应该返回“185103”,但与每个字母的位置相关的数字。(见我的阵列)。目前它没有循环,所以它只为一个字母返回一个索引。这是我到目前为止所拥有的:
print("Please enter the word:")
if let inputCode = readLine(){
let pidgeonCode = ["s", "a", "t", "p", "i", "n", "m", "w", "g", "f", "c", "k"]
let location = pidgeonCode.index(of:inputCode)
print("Your word is: \(location!)")
} else{
print("Type something!!")
}
非常感谢!
解决方案
我设法做到了,谢谢。这是我用于将来帮助的代码。
print("Please enter the word:")
if let inputCode = readLine(){
let numberOf = inputCode.count
var loop = 0
let pidgeonCode = ["@", "s", "a", "t", "p", "i", "n", "m", "d", "g", "o", "c", "k"]
var wordcode = "Code:"
while loop < numberOf{
let x = inputCode.index(inputCode.startIndex, offsetBy: loop)
let result = inputCode[x]
let location = pidgeonCode.index(of:"\(result)")
wordcode = wordcode + "\(location!)"
loop = loop + 1
}
print(wordcode)
} else{
print("Type something!!")
}