w3resource

Swift Basic Programming Exercise: Take the first two characters from a given string and create a new string with the two characters added at both the front and back


Write a Swift program to take the first two characters from a given string and create a new string with the two characters added at both the front and back.

Pictorial Presentation:

Swift Basic Programming Exercise: Take the first two characters from a given string and create a new string with the two characters added at both the front and back.

Sample Solution:

Swift Code:

func front_back_add2(str1: String) -> String {
    let newInput = str1.characters
    let first_2values = newInput.prefix(2)
    let first_two = String(first_2values)
    return first_two + str1 + first_two
}

print(front_back_add2(str1: "swift"))
print(front_back_add2(str1: "abc"))
print(front_back_add2(str1: "ab"))
print(front_back_add2(str1: "a"))

Sample Output:

swswiftsw
ababcab
ababab
aaa

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Swift program to check if a given non-negative number is a multiple of 3 or a multiple of 5.
Next: Write a Swift program to test a given string whether it starts with "Is". Return true or false.

What is the difficulty level of this exercise?

Based on 748 votes, average difficulty level of this exercise is Medium .


Follow us on Facebook and Twitter for latest update.