Search This Blog

Tuesday, October 17, 2017

Reverse every even or every odd word in string in swift

Following task - reverse every even or every odd word in sentence.

Algorithm

  1. Get array of words from string (sentence)
  2. Create new empty string
  3. In for loop go through the array and according to condition reverse word or not and append it to new string
Let's get implemented our algorithm.
import UIKit

let str = "This is the string which will be reverted particaually"

enum WhichNumer: Int {
    case Even = 0
    case Odd = 1
}

func reverseWords(str: String, number: WhichNumer = .Even) -> String {
    let array = str.components(separatedBy: " ")
    var newStr = ""
    for i in 0..<array.count {
        if newStr != "" {
            newStr += " "
        }
        let word = array[i]
        if (i + 1) % 2 == number.rawValue {
            newStr += String(word.reversed())
        } else {
            newStr += word
        }
    }
    
    return newStr
}

print(reverseWords(str: str))
// This si the gnirts which lliw be detrever particaually

print(reverseWords(str: str, number: .Odd))
//sihT is eht string hcihw will eb reverted yllauacitrap

But we can improve our code with using High-ordered function. 

There is following algorithm:

1. Create array of string from initial string
str.components(separatedBy: " ")
// ["This", "is", "the", "string", "which", "will", "be", "reverted", "particaually"]

2. Convert this array to enumerated. According to Apple Documentation after this we can get sequence of pairs with index and value.
"Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero, and x represents an element of the sequence."
str.components(separatedBy: " ").enumerated()
//    0 : This
//    1 : is
//    2 : the
//    3 : string
//    4 : which
//    5 : will
//    6 : be
//    7 : reverted
//    8 : particaually

3. Now we can use map function to this array of pairs. We check index and modify value if needed.
str.components(separatedBy: " ").enumerated().map { (index, value) -> String in
    if ((index + 1) % 2 == number.rawValue) {
        return String(value.reversed())
    }
    return value
})
// ["This", "si", "the", "gnirts", "which", "lliw", "be", "detrever", "particaually"]

4. Finally, array of words can be convert to string with joined function.
let newStr = str.components(separatedBy: " ").enumerated().map { (index, value) -> String in
    if ((index + 1) % 2 == number.rawValue) {
        return String(value.reversed())
    }
    return value
}.joined(separator: " ")
// This si the gnirts which lliw be detrever particaually

Here new implementation of our function.
func reverseWordsUsingHOF(str: String, number: WhichNumer = .Even) -> String {
    let newStr = str.components(separatedBy: " ").enumerated().map { (index, value) -> String in
        print(index)
        if ((index + 1) % 2 == number.rawValue) {
            return String(value.reversed())
        }
        return value
    }.joined(separator: " ")
    
    return newStr
}

print(reverseWordsUsingHOF(str: str))
// This si the gnirts which lliw be detrever particaually

7 comments:

  1. This article impresses me with its well-researched material and good writing. I couldn't put this book down since I was so engrossed in it. Your work and skill have impressed me. Thank you a lot. It can be beneficial to those who want to learn more about Best Custom Websites

    ReplyDelete
  2. You've provided some really useful information; I've been looking for material like this, so please keep sharing it as much as you can. Best Custom Websites

    ReplyDelete
  3. You are providing great content to read. I was looking for this type of unique content. So you resolve my issue. I must appreciate your efforts in providing good reading material.
    Custom Website Development WordPress

    ReplyDelete
  4. Thank you for writing this quality informational content.Your writing technique is impressive and enjoyable to read. I'll come back for more fantastic material.
    Best wishes, and good luck.
    Custom Build Website

    ReplyDelete
  5. your article is unbelievable with accurate information. I see a lot of research after that and that is more than I expectedCustom Build Website

    ReplyDelete
  6. Great share!One of the best blogs I have Ever Seen. Keep going!
    iOS App Testing Services

    ReplyDelete

  7. Great share!One of the best blogs I have Ever Seen. Keep going!
    Affordable SEO Packages New York

    ReplyDelete