How do I get the first or last character of a string in EK9?

← Common String Operations · Ref: Q178

EK9 provides .first() and .last() methods for accessing the first and last characters. For characters at other positions, use stream skip and head.

FIRST CHARACTER

  firstCh <- myString.first()

Returns a Character. Returns unset Character if the string is empty.

LAST CHARACTER

  lastCh <- myString.last()

Returns the last Character.

CHARACTER AT POSITION

Use stream skip and head to extract a character at a specific index:

  thirdChar <- cat myString | skip 2 | head 1 | collect as String

Skip 2, take 1 gives the character at index 2 (zero-based).

SUBSTRING EXTRACTION

Use skip and head for any substring:

  sub <- cat myString | skip 6 | head 5 | collect as String

See Q37 for streamable strings. See Q38 for the Character type. See Q177 for string starts/ends. See Q179 for string fuzzy match.

Example

defines module qa.stringops.firstlast

  defines program
    StringFirstLastDemo()
      stdout <- Stdout()

      greeting <- "Hello World"

      // === FIRST CHARACTER ===

      firstCh <- greeting.first()
      stdout.println(`First: ${firstCh}`)

      // === LAST CHARACTER ===

      lastCh <- greeting.last()
      stdout.println(`Last: ${lastCh}`)

      // === CHARACTER AT POSITION (via stream) ===

      // Get character at index 6 (zero-based)
      charAtSix <- cat greeting | skip 6 | head 1 | collect as String
      stdout.println(`Char at 6: ${charAtSix}`)

      // === SUBSTRING EXTRACTION ===

      // Extract "World" (skip 6, take 5)
      world <- cat greeting | skip 6 | head 5 | collect as String
      stdout.println(`Substring: ${world}`)

      // Extract first 5 characters
      hello <- cat greeting | head 5 | collect as String
      stdout.println(`First 5: ${hello}`)

      // === EMPTY STRING SAFETY ===

      emptyStr <- ""
      emptyFirst <- emptyStr.first()
      emptyLast <- emptyStr.last()
      stdout.println(`Empty first isSet: ${emptyFirst?}`)
      stdout.println(`Empty last isSet: ${emptyLast?}`)

Common mistakes

E50060 — String has no charAt() method. Use .first() for the first character, .last() for the last, or stream skip+head for arbitrary positions. See ek9 -h E50060 for details.

Incorrect:

firstCh <- greeting.charAt(0)

Correct:

firstCh <- greeting.first()
Other ways to ask this
  • How do I extract a single character from a string in EK9?
  • What is the EK9 equivalent of charAt()?
  • How do I access characters by position in EK9?

Coming from another language?

Java: str.charAt(0), str.charAt(str.length()-1). Python: str[0], str[-1]. Rust: str.chars().next(), str.chars().last(). Go: str[0] (byte, not char). JavaScript: str[0], str.at(-1). Kotlin: str.first(), str.last(). EK9: str.first(), str.last(), stream skip+head for any position.

Keywords: char, head, string, last, character, text, position, index, tail, extract, first