如何使用while循环遍历用户输入的单词以查找每个字母的索引

时间:2019-01-24 08:07:50

标签: swift

我是快速编程和尝试使用我想使用的简单方法的新手。香港专业教育学院将随机字母添加到数组,我希望用户键入一个单词。然后,该方法应遍历该单词的每个字母并返回每个字母的索引,以便它将为该单词输出数字代码。例如。如果我输入“ 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!!")

}

非常感谢您!

1 个答案:

答案 0 :(得分:0)

我设法做到了,谢谢。这是我用于将来帮助的代码。

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!!")
}