Start learning free

LESSON 68 OF 291 · STRINGS - CHALLENGES

Concat First and Last Char in Kotlin

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

    KOTLIN · STRINGS - CHALLENGES

    Concat First And Last Char in Kotlin, explained

    Problem overview

    The function concatFirstAndLastChar receives a string s of 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

    A Kotlin string can be indexed with square brackets, and counting starts at 0. The first character is s[0]. The last one sits at index s.length - 1, because a string of length 5 has indexes 0 to 4.

    The only question is how to join the two characters. Indexing gives a Char, not a String, and Char has no + that takes another Char. Writing s[0] + s[s.length - 1] doesn't compile: the compiler reports an argument type mismatch, because the only + on a Char expects an Int.

    A string template solves it. Inside a string literal, ${...} evaluates the expression and inserts its text, so two templates side by side build a two-character string.

    Step by step

    1. Start a string literal with ".
    2. Insert the first character with ${s[0]}.
    3. Insert the last character with ${s[s.length - 1]}.
    4. Close the literal and return it.

    The solution in Kotlin

    class Solution {
        fun concatFirstAndLastChar(s: String): String {
            return "${s[0]}${s[s.length - 1]}"
        }
    }
    

    A few details about this code:

    • Char arithmetic is not text joining. With val c = 'h', the expression c + 1 is the next character, 'i': adding an Int to a Char moves along the alphabet. That is why Char + Char is rejected instead of being treated as concatenation.
    • Other ways to join. s[0].toString() + s[s.length - 1] works too, because String + Char is allowed and gives a String. So does "" + s[0] + s[s.length - 1]. For "hello" both give "ho".
    • first() and last(). Kotlin also offers s.first() and s.last(), which return the same two characters without index arithmetic.
    • Characters, not bytes. Indexing counts UTF-16 units, which is the same as characters for the English letters, digits and punctuation this lesson uses.

    Tracing the examples

    For "hello", s.length is 5, so the last index is 4. s[0] is 'h' and s[4] is 'o'. The two templates each insert one character, and the result is "ho", a string of length 2.

    For "Hello World!", s.length is 12 and s[11] is '!'. The space in the middle and the letters around it play no part: only the two ends are read, and the answer is "H!".

    The same two lines of reasoning cover every input, whatever the length. That is why one expression is enough and no loop or condition is needed.

    Edge cases and common mistakes

    • Using s.length as the last index. The valid indexes stop at s.length - 1. Index s.length throws a StringIndexOutOfBoundsException.
    • Adding the two characters. s[0] + s[s.length - 1] fails to compile, as described above. If it did compile, adding character codes would give a number, not a string: 'h'.code + 'o'.code is 215.
    • Empty strings. The lesson promises at least two characters. On an empty string, s[0] throws StringIndexOutOfBoundsException too.
    • Changing the case. Nothing here converts letters. The H in "Hello World!" stays upper case.

    Testing

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