Start learning free

LESSON 68 OF 292 · STRINGS - CHALLENGES

Concat First and Last Char in Swift: prefix and suffix

Practice Read the full explanation

Given a string s, return a new string made of two characters: the first character of s, followed by its last character.

 

Example 1:

Input: s = "hello"
Output: "ho"
Explanation: The first character is "h" and the last one is "o".

Example 2:

Input: s = "Hello World!"
Output: "H!"
Explanation: Every character counts, so the last one is the "!", not the "d". The "H" stays upper case.

Example 3:

Input: s = "ab"
Output: "ab"
Explanation: With only two characters, the first is "a" and the last is "b".

 

Constraints:

  • s has at least 2 characters.
  • s contains English letters, digits, spaces and punctuation, and doesn't start or end with a space.
STEP 1 OF 1
    Ctrl + Enter to check

    SWIFT · STRINGS - CHALLENGES

    Concat First And Last Char in Swift, explained

    Problem overview

    The function concatFirstAndLastChar receives a string s with at least two characters and returns a new two-character string: the first character of s followed by its last character.

    For "hello" the answer is "ho". For "Hello World!" it is "H!": every character counts, so the last one is the exclamation mark, and the capital H stays a capital. For "ab" the first and last characters are the whole string, so the answer is "ab".

    Approach: ask for characters from each end

    In many languages you would write s[0] and s[s.length - 1]. Swift does not allow that. A String can't be indexed with an Int, and this code is rejected by the compiler:

    let s = "hello"
    print(s[0])
    

    The error says that you cannot subscript a String with an Int and should use a String.Index instead. The reason is that a Swift character can be built from several Unicode pieces, so the n-th character is not at a fixed offset. Finding it means walking through the string.

    The lesson avoids indexes completely. prefix(n) keeps the first n characters and suffix(n) keeps the last n. With n equal to 1, each gives exactly the character you need, and neither needs the length.

    Another way: Character and String.Index

    Indexes do exist in Swift; they are just not integers. s.startIndex is the position of the first character, and s.index(before: s.endIndex) is the position of the last one. Subscripting with them gives a Character, and String(...) turns each one into a string:

    let s = "hello"
    let first = s[s.startIndex]
    let last = s[s.index(before: s.endIndex)]
    print(String(first) + String(last)) // ho
    

    There are also the properties s.first and s.last, but they return an optional Character, because an empty string has no first or last character. Using ! to unwrap them would crash on an empty string. prefix(1) and suffix(1) return an empty result there instead, which is why the lesson prefers them: shorter and safe.

    Step by step

    1. Take the first character with s.prefix(1).
    2. Take the last character with s.suffix(1).
    3. Convert each one to a String. Both calls return a Substring, a view into the original string, and the function must return a String.
    4. Join the two strings with + and return the result.

    The solution in Swift

    class Solution {
        func concatFirstAndLastChar(_ s: String) -> String {
            return String(s.prefix(1)) + String(s.suffix(1))
        }
    }
    

    Details worth knowing:

    • Why String(...) is needed. "hello".prefix(1) has the type Substring. Writing return s.prefix(1) + s.suffix(1) fails to compile with an error that it cannot convert the return expression of type String.SubSequence (aka Substring) to return type String. Wrapping each piece in String(...) makes a real, independent string.
    • Characters, not bytes. prefix and suffix count Swift characters. A letter written as e followed by a combining accent is one character, so it is kept whole instead of being split in two.
    • It never goes out of range. If n is bigger than the string, prefix(n) and suffix(n) return the whole string. An index would trap at run time instead.

    Edge cases and common mistakes

    • Two characters. "ab" gives "ab", as the example shows.
    • Punctuation and digits. "a9" gives "a9", and "Hello World!" gives "H!": the function never skips characters that aren't letters.
    • Forgetting the conversion. Returning a Substring where a String is expected is the most common compile error here.
    • Using prefix(2) by mistake. That keeps two characters from the front, which is not the same as the first and last.

    Testing

    • "hello" gives "ho".
    • "Hello World!" gives "H!".
    • "ab" gives "ab".
    • "a9" gives "a9".
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free