Start learning free

LESSON 72 OF 292 · STRINGS - CHALLENGES

Repeat Last Char in Swift: suffix and String(repeating:count:)

Practice Read the full explanation

Given a string s and a number n, return a new string made of the last character of s, written n times in a row.

 

Example 1:

Input: s = "banana", n = 3
Output: "aaa"
Explanation: The last character of "banana" is "a". Written 3 times, it gives "aaa".

Example 2:

Input: s = "Wow!", n = 2
Output: "!!"
Explanation: The last character can be any character: here it is the exclamation mark.

Example 3:

Input: s = "z", n = 1
Output: "z"
Explanation: A string of one character: its last character is "z", written once.

 

Constraints:

  • s has at least one character and doesn't start or end with a space.
  • s contains English letters, digits, spaces and punctuation.
  • n is a whole number from 1 to 10.
STEP 1 OF 1
    Ctrl + Enter to check

    SWIFT · STRINGS - CHALLENGES

    Repeat Last Char in Swift, explained

    Problem overview

    The function repeatLastChar receives a string s and a whole number n from 1 to 10. It returns a new string made of the last character of s, written n times in a row.

    For "banana" and n = 3 the last character is a, so the answer is "aaa". For "Wow!" and n = 2 it is "!!": the last character can be any character, punctuation included. For "z" and n = 1 the string has a single character, which is also its last one, so the answer is "z".

    Approach: find the last character, then repeat it

    The task splits into two jobs. First get the last character of s. Swift strings can't be indexed with integers, so s[s.count - 1] doesn't compile. The method suffix(1) keeps the last character instead and needs no length. Second, write that character n times. Swift has an initializer for exactly that: String(repeating:count:). For example, String(repeating: "ab", count: 3) is "ababab", and a count of 0 gives an empty string.

    Step by step

    1. Take the last character with s.suffix(1).
    2. Convert it to a String with String(...). suffix returns a Substring, and String(repeating:count:) works on a String.
    3. Repeat it n times with String(repeating: ..., count: n) and return the result.

    The solution in Swift

    class Solution {
        func repeatLastChar(_ s: String, _ n: Int) -> String {
            return String(repeating: String(s.suffix(1)), count: n)
        }
    }
    

    Details worth knowing:

    • Two String(...) calls with different jobs. The inner one converts the Substring from suffix(1) into a String. The outer one, String(repeating:count:), builds the repeated text. The argument labels repeating: and count: are required.
    • The unit that repeats can be longer than one character. The first argument is repeated whole, so the same initializer also repeats words or patterns.
    • The count must not be negative. A negative count stops the program at run time. The lesson keeps n between 1 and 10, so this isn't a concern here.
    • There is no loop. The same result could be built by appending to a var inside a for loop, but the initializer says what you mean in one line.

    Variations

    There is a second way to get the last character. The property s.last returns an optional Character, because an empty string has no last character. With a ! to unwrap it, String(repeating: s.last!, count: n) also works, because String has a version of the initializer that takes a Character. For "banana" and n = 3 it gives "aaa". The ! stops the program on an empty string, though, while suffix(1) simply gives an empty result there. The lesson guarantees at least one character, but the safer version is the better habit.

    The initializer is also what you would reach for when you need padding, a separator line such as a row of dashes, or an indent made of spaces: it takes a piece of text and a count, and nothing else.

    Edge cases and common mistakes

    • One-character strings. "z" with n = 1 gives "z".
    • A non-letter at the end. "Wow!" gives "!!" for n = 2: don't look for the last letter, only the last character.
    • Using prefix(1). That repeats the first character, so "banana" would give "bbb".
    • Leaving out the labels. String("a", 3) doesn't compile; write String(repeating: "a", count: 3).
    • Passing the Substring directly. It is easy to forget the inner String(...). Wrapping the result of suffix(1) first keeps the types simple.

    Testing

    • "banana", n = 3 gives "aaa".
    • "Wow!", n = 2 gives "!!".
    • "z", n = 1 gives "z".
    • "hi5", n = 4 gives "5555".
    • "a b!", n = 10 gives "!!!!!!!!!!".
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free