w3resource
swift Programming Exercises

Swift String Exercises: Return the first half of a given string of even length

Swift String Programming: Exercise-5 with Solution

Write a Swift program to return the first half of a given string of even length.

Pictorial Presentation:

Flowchart: Swift String Exercises - Return the first half of a given string of even length.

Sample Solution:

Swift Code:

func first_half_str(_ input: String) -> String {
    let chars = input.characters
    let first_half = chars.prefix(input.characters.count / 2)
    
    return String(first_half)
}
print(first_half_str("Java"))
print(first_half_str("Python"))

Sample Output:


Ja
Pyt

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 a copy of the first two characters of a given string. If the given string is shorter than length 2, return whatever there is.
Next: Write a Swift program to create a new string without the first and last character of a given string. The string length must be at least 2.

What is the difficulty level of this exercise?