【发布时间】:2016-02-03 00:56:28
【问题描述】:
我对 swift 比较陌生。我正在尝试制作一个程序,该程序采用单词列表(以字符串数组的形式)并删除不包含用户选择的字母的字符串。所以,如果词表是 ["apple", "banana", "cherry", "date", "endive"] 并且用户选择了字母 "a" (这是变量 "centerletter"), "apple", "banana" 和 "date" 将被返回,因为它们确实包含字母 a。当输入的数组(wordlist)是标准数组,如 ["apple", "banana"] 时,此代码有效。但是,我对这段代码的实际用途是对英语中的每个单词进行排序,如我的文件“words.txt”(我的 swift 项目中的文件之一)中所示。
我已将 words.txt 中的每个单词(由 /n 分隔)分配给 wordlist,如下所示(这是函数):
func arrayFromContentsOfFileWithName(fileName: String) -> [String]? {
let path = NSBundle.mainBundle().pathForResource("words", ofType: "txt")
var fileContents: String? = nil
do {
fileContents = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
return fileContents!.componentsSeparatedByString("\n")
} catch _ as NSError {
return nil
}
}
我将 wordlist 分配给 arrayFromContentsOfFileWithName("words.txt") 的结果,如下所示:
var wordlist = arrayFromContentsOfFileWithName("words.txt")
然后我使用此代码处理单词列表(尝试取出单词列表中不包含用户选择的字母(在我的示例中为“a”)的每个单词。此代码适用于标准数组,例如 ["apple", "banana"],但不在使用函数 arrayFromContentsOfFileWithName 制作的数组上。
let centerlet:Character = Character(Array(arrayLiteral: centerletter.text!)[0])
// centerlet 是用户选择的字母。
for var i = 0; i < wordlist?.count; i++ {
if wordlist![i].characters.contains(centerlet) {
print("I am leaving in \(wordlist![i]) because it contains the center letter")
} else {
print("I removed \(wordlist![i]) because it did not have the center letter.")
wordlist?.removeAtIndex(i)
}
}
如何将 words.txt 中的所有单词转换为标准的 swift 数组,以便删除所述数组中不包含特定字母的每个单词?谢谢。
【问题讨论】:
-
我什至尝试将
if wordlist![i].characters.contains(centerlet) {行更改为更可选的if ((wordlist?[i].characters.contains(centerlet)) != nil) {。然后它留在每个单词中,即使它不包含用户选择的字母。 -
我尝试替换 .characters.contains = .containsString,但没有成功。这基本上是一样的(.characters.contains = .containsString,因为我正在搜索 1 个字符的字符串)。我试过了,还是不行;要么全部否定,要么全部肯定,这取决于我做出 if 语句的可选性(请参阅我的第一条评论)。
-
删除了之前的评论,因为我想到了同样的事情 :) 这似乎是 Swift 的函数式方法使用
.filter或.map通过返回结果将一个数组转换为另一个数组的完美案例从一个闭包中......这基本上是我在输入这个时 Mundi 在下面写的...... -
向后遍历单词数组:
i = ...count-1; i >= 0; i-- -
建议编辑问题以发布文本文件,或者 wordList 和 centerLetter 的来源。