Write a Swift program to create a string made of two copies of the last two characters of a given string

Introduction

I have used Swift for windows 1.9 for debugging purpose. But you can use any Swift programming language compiler as per your availability.

import Foundation
func new_string(_ str: String) -> String {
    var result = ""
    var last_two_index = str.endIndex
 
    for _ in 0..<2 {
        last_two_index = str.index(before: last_two_index)
    }
 
    let last_2_chars = str.substring(from: last_two_index)
 
    for _ in 0..<2 {
        result.append(last_2_chars)
    }
 
    return result
}
 
print(new_string("tech"))
print(new_string("study"))

Result

Write a Swift program to create a string made of two copies of the last two characters of a given string
Write a Swift program to create a string made of two copies of the last two characters of a given string

Leave a Comment