如何逐个处理单词?

时间:2015-06-27 17:52:10

标签: ios swift

如何从段落中选择单词并逐个处理。我想换掉第一个和最后一个字母以外的字母。我怎么能够? 感谢

var fullInputArray = []
func convertToArray(){
    let fullInput = inputBox.text
    fullInputArray = fullInput.componentsSeparatedByString(" ")
    println("\(fullInputArray)") //prints [hello, world, this, is, an, app]
}


func processWords(){
    var processedArray: [String] = //something functional code like fullInputArray.mix
    println("\(processedArray)") //prints [hlleo, wlord, tihs, is, an, app]
}

2 个答案:

答案 0 :(得分:1)

您可以将paragraph(String)拆分为Array,然后访问该Array索引。

尝试此答案将您的字符串转换为数组:https://stackoverflow.com/a/26270721/3411787

答案 1 :(得分:1)

import UIKit

extension Array {
    var shuffled: [T] {
        var result = self
        for index in 0..<result.count-1 {
            swap(&result[index], &result[Int(arc4random_uniform(UInt32(result.count-index)))+index])
        }
        return result
    }
}

extension String {
    var wordList:[String] {
        return "".join(componentsSeparatedByCharactersInSet(NSCharacterSet.punctuationCharacterSet())).componentsSeparatedByString(" ")
    }
    var first: String {
        return String(self[startIndex])
    }
    var last: String {
        return String(self[endIndex.predecessor()])
    }
    var scrambleMiddle: String {
        if count(self) < 4 {
            return self
        }
        return first + String(Array(dropLast(dropFirst(self))).shuffled) + last
    }
}


let myWordListScrambled = "Hello Playground".wordList.map{$0.scrambleMiddle}

println(myWordListScrambled)   // "[Hlelo, Plnrgayoud]"

注意:此answer

的随机扩展变体