我正在尝试使用Swift遍历整个字母表。唯一的问题是我想为每个字母赋值。
例如:a = 1,b = 2,c = 3,依此类推,直到我到达z = 26。
如何使用先前分配给字母表中字母的值,在用户输入的文本字段中查看每个字母?
完成此操作后,如何将所有字母值相加以获得整个单词的总和。我正在寻找最简单的方法来实现这一点,但按照我希望的方式工作。
有什么建议吗?
先谢谢。
答案 0 :(得分:6)
编辑/更新: Xcode 7.2.1•Swift 2.1.1
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var strWordValue: UILabel!
@IBOutlet weak var strInputField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func sumLettersAction(sender: AnyObject) {
strWordValue.text = strInputField.text?.wordValue.description
}
}
扩展
extension String {
var letterValue: Int {
return Array("abcdefghijklmnopqrstuvwxyz".characters).indexOf(Character(lowercaseString))?.successor() ?? 0
}
var wordValue: Int {
var result = 0
characters.forEach { result += String($0).letterValue }
return result
}
}
func letterValue(letter: String) -> Int {
return Array("abcdefghijklmnopqrstuvwxyz".characters).indexOf(Character(letter.lowercaseString))?.successor() ?? 0
}
func wordValue(word: String) -> Int {
var result = 0
word.characters.forEach { result += letterValue(String($0)) }
return result
}
let aValue = letterValue("a") // 1
let bValue = letterValue("b") // 2
let cValue = letterValue("c") // 3
let zValue = letterValue("Z") // 26
let busterWordValue = wordValue("Buster") // 85
let busterWordValueString = wordValue("Buster").description // "85"
//
extension Character {
var lowercase: Character { return Character(String(self).lowercaseString) }
var value: Int { return Array("abcdefghijklmnopqrstuvwxyz".characters).indexOf(lowercase)?.successor() ?? 0 }
}
extension String {
var wordValue: Int { return Array(characters).map{ $0.value }.reduce(0){ $0 + $1 } }
}
"Abcde".wordValue // 15
答案 1 :(得分:0)
我会创建一个像这样的函数......
func valueOfLetter(inputLetter: String) -> Int {
let alphabet = ["a", "b", "c", "d", ... , "y", "z"] // finish the array properly
for (index, letter) in alphabet {
if letter = inputLetter.lowercaseString {
return index + 1
}
}
return 0
}
然后你可以迭代这个词......
let word = "hello"
var score = 0
for character in word {
score += valueOfLetter(character)
}
答案 2 :(得分:0)
通过迭代字母并使用与其各自值对应的字母构建字典来分配字母:
let alphabet: [String] = [
"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 alphaDictionary = [String: Int]()
var i: Int = 0
for a in alphabet {
alphaDictionary[a] = ++i
}
使用Swift的内置数组reduce
功能来总结从UITextViewDelegate
返回的字母:
func textViewDidEndEditing(textView: UITextView) {
let sum = Array(textView.text.unicodeScalars).reduce(0) { a, b in
var sum = a
if let d = alphaDictionary[String(b).lowercaseString] {
sum += d
}
return sum
}
}
答案 3 :(得分:0)
也许你正在寻找这样的东西:
func alphabetSum(text: String) -> Int {
let lowerCase = UnicodeScalar("a")..."z"
return reduce(filter(text.lowercaseString.unicodeScalars, { lowerCase ~= $0}), 0) { acc, x in
acc + Int((x.value - 96))
}
}
alphabetSum("Az") // 27 case insensitive
alphabetSum("Hello World!") // 124 excludes non a...z characters
序列text.lowercaseString.unicodeScalars
(作为unicode标量的小写文本)被过滤filter
,只保留模式匹配 ~=
的标量与lowerCase
} 范围。
reduce
将所有已过滤的标量值已移位与-96相加(这样' a'给出1等)。 reduce
从累加器(acc
)值0
开始。
在此解决方案中,模式匹配运算符将仅检查标量值是否在lowerCase.start
(a)和lowerCase.end
(z)之间,因此不会查找或循环到字符数组中。
答案 4 :(得分:0)
我刚刚在swiftstub.com上整理了以下功能,它似乎按预期工作。
func getCount(word: String) -> Int {
let alphabetArray = Array(" abcdefghijklmnopqrstuvwxyz")
var count = 0
// enumerate through each character in the word (as lowercase)
for (index, value) in enumerate(word.lowercaseString) {
// get the index from the alphabetArray and add it to the count
if let alphabetIndex = find(alphabetArray, value) {
count += alphabetIndex
}
}
return count
}
let word = "Hello World"
let expected = 8+5+12+12+15+23+15+18+12+4
println("'\(word)' should equal \(expected), it is \(getCount(word))")
// 'Hello World' should equal 124 :)
该函数遍历传递给它的字符串中的每个字符,并使用find
函数检查序列(alphabetArray)中是否存在字符(值),如果是,则返回索引从序列。然后将索引添加到计数中,并且当检查了所有字符时,返回计数。