w3resource

Swift String Exercises: Check if the first or last characters are 'a' of a given string, return the given string without those 'a' characters

Swift String Programming: Exercise-21 with Solution

Write a Swift program to check if the first or last characters are 'a' of a given string, return the given string without those 'a' characters, and otherwise return the given string.

Pictorial Presentation:

Flowchart: Swift String Exercises - Check if the first or last characters are 'a' of a given string, return the given string without those 'a' characters.

Sample Solution:

Swift Code:

import Foundation
func str_without_a(_ str1:String) -> String {
    var new_str = str1
    
    if new_str.hasPrefix("a") 
    {
        new_str.characters.removeFirst()
    }
    
    if new_str.hasSuffix("a")
    {
        new_str.characters.removeLast()
    }
    
    return new_str
}
print(str_without_a("abcda"))
print(str_without_a("bcd"))

Sample Output:


bcd
bcd

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Swift program to create a new string made of 2 copies of the first 2 characters of a given string. The string may be any length.

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-21.php