w3resource

Swift String Exercises: Insert a given string to another given string where the second string will be in the middle of the first string


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.

Pictorial Presentation:

Flowchart: Swift String Exercises - Insert a given string to another given string where the second string will be in the middle of the first string.

Sample Solution:

Swift Code:

func insert_string(_ str1: String, _ str2: String) -> String {
    var current_index = str1.startIndex
    let char1: Character = str1[current_index]
    var result = str1
    
    while char1 == str1[current_index] {
        current_index = str1.index(after: current_index)
    }
    
    result.insert(contentsOf: str2.characters, at: current_index)
    
    return result
}

print(insert_string("<>", "Swift"))
print(insert_string("<>>", "Swift"))
print(insert_string("[]", "Swift"))

Sample Output:

<Swift>
<Swift>>
[Swift]

Go to:


PREV : Write a Swift program to draw a HTML string as bold or italic text.
NEXT : Write a Swift program to create a new string made of two copies of the first two characters of a given string. If the given string is shorter than length 2, return whatever there is.

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.