w3resource

Swift String Exercises: Create a new string of any length from a given string where the last two characters are swapped

Swift String Programming: Exercise-17 with Solution

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.

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?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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/string/swift-string-exercise-17.php