w3resource
swift Programming Exercises

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?