LEN
Syntax
LEN(string$)Source:
pb_cg_emit_len_builtin (pb_codegen.c:4108)Description
Returns the number of characters in string$, excluding the NUL terminator. LEN is one of the most frequently used string functions, essential for loops, bounds checking, buffer management, and validation logic.
For string literals, the length is a compile-time constant and the compiler emits an immediate value. For local STRING variables, the length is read from the string descriptor in the stack frame. For STATIC or GLOBAL strings, the length is read from a labeled data slot. For BYREF parameters, the length is obtained by dereferencing the pointer to the descriptor.
An empty string ("") returns 0. The NUL terminator is never counted. LEN is complementary to SIZEOF which returns the byte size of a data type or variable rather than the string character count.
Parameters
| Parameter | Description |
|---|---|
string$ | The STRING expression whose length is to be determined. Can be a literal, local variable, STATIC/GLOBAL variable, or BYREF parameter. |
Return Value
An integer (LONG) representing the number of characters in string$. Returns 0 for an empty string.
Example
FUNCTION PBMAIN() AS LONG
LOCAL s AS STRING
LOCAL n AS LONG
' Basic usage
s = "Hello World"
n = LEN(s) ' n = 11
PRINT "Length: "; n
' Empty string
s = ""
n = LEN(s) ' n = 0
PRINT "Empty length: "; n
' String literal (compile-time constant)
n = LEN("PowerBASIC") ' n = 10
PRINT "Literal length: "; n
' Loop through string characters
s = "ABCDEF"
FOR n = 1 TO LEN(s)
PRINT "Char "; n; ": "; MID$(s, n, 1)
NEXT n
' Validation: check minimum length
s = "AB"
IF LEN(s) < 3 THEN
PRINT "String too short (min 3 chars)"
END IF
' Extract last character using LEN
s = "Hello World"
PRINT "Last char: "; RIGHT$(s, 1) ' using RIGHT$ with LEN
PRINT "Also: "; MID$(s, LEN(s), 1) ' using MID$ with LEN
' Truncation check
s = "This is a very long string that exceeds limits"
IF LEN(s) > 20 THEN
PRINT "Truncated: "; LEFT$(s, 20); "..."
END IF
FUNCTION = 0
END FUNCTION
Generated Assembly
pb_cg_emit_len_builtin (pb_codegen.c:4108); String literal: constant mov rax, <literal_length> ; Local STRING: load from descriptor mov rax, [rbp - length_offset] ; length slot in frame ; STATIC/GLOBAL STRING: load from static data mov rax, [<label>_len]
Notes
LENreturns the logical character count, not the byte size. For ASCII strings these are the same; for WSTRING (UTF-16) they differ.- The length is stored in the string descriptor alongside the data pointer. It is maintained by all string operations (assignment, concatenation, string functions).
- For string literals, the compiler computes the length at compile time and emits an immediate
MOV, making it a zero-cost operation. LENis commonly used withMID$andRIGHT$to work with relative positions from the end of a string.- Do not confuse
LEN(string character count) withSIZEOF(byte size of a type or variable).