Extract the first and last characters from a string.
← Operators and Expressions · Ref: Q1166
Use the prefix (#<) and suffix (#>) operators:
firstChar <- #< name lastChar <- #> name
The #< operator returns the first character (as a Character) and #> returns the last character. These are introspection operators available on String. See Q242 for conversion and introspection operators. See Q238 for the complete operator set.
Example
defines module qa.operators.substringextract defines program SubstringExtractDemo() stdout <- Stdout() name <- "Hello" // Extract first and last characters firstChar <- #< name lastChar <- #> name stdout.println(`First: ${firstChar}`) stdout.println(`Last: ${lastChar}`) // Use with different strings words <- ["EK9", "World", "A"] for word in words first <- #< word last <- #> word stdout.println(`'${word}' -> first: ${first}, last: ${last}`) // Length for context size <- length name stdout.println(`Length of '${name}': ${size}`)
Common mistakes
E50060 — String has no charAt() method. Use the #< prefix operator to get the first character and #> suffix operator for the last character. See ek9 -h E50060 for details.
Incorrect:
firstChar <- name.charAt(0)
Correct:
firstChar <- #< name
Other ways to ask this
- Write code to get the prefix and suffix characters of a string
- I have a string and need its first character and last character separately
- Given a name string, extract the initial and final characters using operators
- In Java I'd use charAt(0) and charAt(length-1). Write the EK9 equivalent
Coming from another language?
Java: str.charAt(0) and str.charAt(str.length()-1). Python: str[0] and str[-1]. Rust: str.chars().next() and str.chars().last(). Go: str[0] and str[len(str)-1]. EK9: #< str and #> str — prefix and suffix operators.
Keywords: prefix, first, last, extract, character, suffix, introspection, operator, string