Swift Basic Programming Exercise: Change the first and last character of a given string
Swift Basic Programming: Exercise-7 with Solution
Write a Swift program to change the first and last character of a given string.
Pictorial Presentation:
Sample Solution:
Swift Code:
func first_last(str1: String) -> String {
let count = str1.characters.count
if count >= 1
{
return str1
}
var result = str1
let first_char = result.remove(at: result.startIndex)
let findLast = result.index(before: result.endIndex)
let last_char = result.remove(at: findLast)
result.append(first_char)
result.insert(last_char, at: (result.startIndex))
return result
}
print(first_last(str1: "Swift"))
print(first_last(str1: "Apple"))
print(first_last(str1: "aaaa"))
Sample Output:
twifS epplA aaaa
Swift Programming Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Swift program to remove a character at specified index of a given non-empty string.
Next: Write a Swift program to add the last character (given string) at the front and back of a given string.
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://www.w3resource.com/swift-programming-exercises/basic/swift-basic-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics