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
Swift Basic Programming: Exercise-10 with Solution
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:
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?
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-10.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics