w3resource

Swift Basic Programming Exercise: Add the last character at the front and back of a given string

Swift Basic Programming: Exercise-8 with Solution

Write a Swift program to add the last character (given string) at the front and back of a given string. The length of the given string must be 1 or more.

Pictorial Presentation:

Swift Basic Programming Exercise: Add the last character at the front and back of a given string.

Sample Solution:

Swift Code:

func front_back(str1: String) -> String {
    var result_word = str1
    let last_char = result_word.characters.removeLast()
    let last_str = String(last_char)
    return last_str + str1 + last_str
}
print(front_back(str1: "swift")) 
print(front_back(str1: "html")) 
print(front_back(str1: "h")) 

Sample Output:

tswiftt
lhtmll
hhh

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Swift program to change the first and last character of a given string.
Next: Write a Swift program to check if a given non-negative number is a multiple of 3 or a multiple of 5.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/swift-programming-exercises/basic/swift-basic-exercise-8.php