-2

how can I pick words from a paragraph and process one by one. I want to switch places of letters except first and last letter. How can I? Thanks

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]
}
Encul
  • 93
  • 1
  • 10

2 Answers2

1

You can split paragraph(String) into Array ,then access that Array indexes.

Try this answer to convert your String to Array :https://stackoverflow.com/a/26270721/3411787

Community
  • 1
  • 1
Mohammad Zaid Pathan
  • 15,352
  • 7
  • 92
  • 124
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]"

Note: Shuffle Extension variation from this answer

Community
  • 1
  • 1
Leo Dabus
  • 216,610
  • 56
  • 458
  • 536
  • Should I add this code outside of ViewController class? Otherwise I'm getting an error(Decleration is only valid at file scope). Thus, I added it outside of ViewController class. But in that case, I cannot call UITextField instead of "Hello Playground"(myWordListScrambled). How can I fix it? – Encul Jun 27 '15 at 20:34
  • Yes all extensions must be placed out of your view controller. – Leo Dabus Jun 27 '15 at 20:37
  • Ok thanks. But how can I use inputBox instead of "Hello Playground"(myWordListScrambled)? I tried ViewController().inputBox but I got an error(UITextView does not have a member named 'wordList') – Encul Jun 27 '15 at 20:50
  • Hi, how can I use that code in swift 2.0? @LeoDabus – Encul Jul 25 '15 at 09:33