How do I get the length of a string in EK9?
← Common String Operations · Ref: Q170
EK9 provides two ways to get string length and a dedicated empty check.
LENGTH OPERATOR
Prefix operator syntax:
len <- length myString
Returns the number of characters.
METHOD SYNTAX
len <- myString.length()
Equivalent to the operator form.
EMPTY CHECK
Test whether a string has no characters:
if myString is empty stdout.println("No content")
Note: an empty string (length 0) IS set. An unset string is different from an empty string.
See Q37 for comprehensive string operations. See Q29 for the distinction between empty and unset. See Q242 for conversion and introspection operators including length.
Example
defines module qa.stringops.length defines program StringLengthDemo() stdout <- Stdout() greeting <- "Hello World" // === LENGTH OPERATOR === len1 <- length greeting stdout.println(`Length (operator): ${len1}`) // === METHOD SYNTAX === len2 <- greeting.length() stdout.println(`Length (method): ${len2}`) // === EMPTY CHECK === emptyStr <- "" stdout.println(`Empty string length: ${length emptyStr}`) stdout.println(`Is empty: ${emptyStr is empty}`) // Empty string IS set (not unset) require emptyStr? stdout.println(`Empty string isSet: ${emptyStr?}`) // Non-empty check if ~greeting is empty stdout.println("Greeting has content") // === UNSET STRING === unsetStr <- String() stdout.println(`Unset string isSet: ${unsetStr?}`)
Common mistakes
E50060 — String has no size() method. Use the length prefix operator or .length() method. See ek9 -h E50060 for details.
Incorrect:
len1 <- greeting.size()
Correct:
len1 <- length greeting
Other ways to ask this
- How do I count the characters in a string in EK9?
- What is the EK9 equivalent of string.length()?
- How do I check if a string is empty in EK9?
Coming from another language?
Java: str.length(), str.isEmpty(). Python: len(str), not str for empty check. Rust: str.len(), str.is_empty(). Go: len(str). JavaScript: str.length property. Kotlin: str.length, str.isEmpty(). EK9: length str or str.length(), str is empty.
Keywords: length, string, empty, count, characters, text, size