Swift String Exercises: Create a new string of any length from a given string where the last two characters are swapped
Write a Swift program to create a new string of any length from a given string where the last two characters are swapped, so 'abcde' will be 'abced'.
Pictorial Presentation:
![Flowchart: Swift String Exercises - Create a new string of any length from a given string where the last two characters are swapped.](https://www.w3resource.com/w3r_images/swift-string-image-exercise-17.png)
Sample Solution:
Swift Code:
func string_swap(_ a:String) -> String {
var str1 = a
let last_char = str1.characters.removeLast()
let second_to_lastchar = str1.characters.removeLast()
str1.append(last_char)
str1.append(second_to_lastchar)
return str1
}
print(string_swap("abcde"))
print(string_swap("12345"))
Sample Output:
abced 12354
Swift Programming Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Swift program to concat two given strings and return the new string. If the new string creates a double character then omit one of the character. so "vwx" and "xyz" will return "vwxyz".
Next: Write a Swift program to return "abc" or "xyz" if a given string begins with "abc" or "xyz" otherwise return the empty string.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics