w3resource

Swift String Exercises: Check if the first two characters are same of the last two characters of a given string

Swift String Programming: Exercise-19 with Solution

Write a Swift program to check if the first two characters are same of the last two characters of a given string.

Pictorial Presentation:

Flowchart: Swift String Exercises - Check if the first two characters are same of the last two characters of a given string.

Sample Solution:

Swift Code:

func front_end(_ a:String) -> Bool {
    
    if String(a.characters.prefix(2)) == String(a.characters.suffix(2)) 
    {
        return true
    } 
    else 
    {
        return false
    }
}
print(front_end("abcdefab"))
print(front_end("abcdefba"))
print(front_end(""))

Sample Output:


true
false
true

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous: 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'.
Next: 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://www.w3resource.com/swift-programming-exercises/string/swift-string-exercise-19.php