Swift String Exercises: Move the last two characters of a given string to the start
Swift String Programming: Exercise-10 with Solution
Write a Swift program to move the last two characters of a given string to the start. The given string length must be at least 2.
Pictorial Presentation:
Sample Solution:
Swift Code:
func last_to_first(_ str1: String) -> String {
var chars = str1.characters
let last_char = chars.removeLast()
let rest_part = chars.removeLast()
chars.insert(last_char, at: chars.startIndex)
chars.insert(rest_part, at: chars.startIndex)
return String(chars)
}
print(last_to_first("Swift"))
print(last_to_first("Python"))
Sample Output:
ftSwi onPyth
Swift Programming Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Swift program to move the first two characters of a given string to the end. The given string length must be at least 2.
Next: Write a Swift program to create a new string without the first and last character of a given string. The string may be any length, including 0.
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/string/swift-string-exercise-10.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics