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.


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

  1. import Foundation
  2. func new_string(_ str: String) -> String {
  3. var result = ""
  4. var last_two_index = str.endIndex
  5.  
  6. for _ in 0..<2 {
  7. last_two_index = str.index(before: last_two_index)
  8. }
  9.  
  10. let last_2_chars = str.substring(from: last_two_index)
  11.  
  12. for _ in 0..<2 {
  13. result.append(last_2_chars)
  14. }
  15.  
  16. return result
  17. }
  18.  
  19. print(new_string("tech"))
  20. print(new_string("study"))

Result

swift programming languages techstudy.org

     





Related Topics





Popular Posts