Write a Swift program to insert a given string to another given string where the second string will be in the middle of the first 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. func insert_string(_ str1: String, _ str2: String) -> String {
  2. var current_index = str1.startIndex
  3. let char1: Character = str1[current_index]
  4. var result = str1
  5.  
  6. while char1 == str1[current_index] {
  7. current_index = str1.index(after: current_index)
  8. }
  9.  
  10. result.insert(contentsOf: str2.characters, at: current_index)
  11.  
  12. return result
  13. }
  14.  
  15. print(insert_string("<>", "Swift"))
  16. print(insert_string("<>>", "Swift"))
  17. print(insert_string("[]", "Swift"))

Result

swift programming languages techstudy.org

     





Related Topics





Popular Posts