string-ref(3scm) Scheme Programmer's Manual string-ref(3scm)

string-ref - get a character from a string

(import (rnrs))                     ;R6RS
(import (rnrs base))                ;R6RS
(import (scheme r5rs))              ;R7RS
(import (scheme base))              ;R7RS

(string-ref string k)

Returns character k of string using zero-origin indexing.
R6RS
Implementors should make string-ref run in constant time.
R7RS
There is no requirement for this procedure to execute in constant time.

Chibi Scheme
Chibi supports O(1) string access if the SEXP_USE_STRING_INDEX_TABLE feature is enabled.

Returns a single value which is a character object. It is eqv?(3scm) to the one that was last placed in the string at index k.

(string-ref "abc" 1)  =>  #\b

This procedure is used to implement algorithms that read strings in non-linear access patterns. Programs that read strings at increasing indices can use open-string-input-port(3scm) instead.

The choice of R7RS to not require execution in constant time opens the possibility for implementations to use UTF-8 or UTF-16 as the internal string representation.

This procedure is functionally the same in all RnRS revisions after R2RS. The differences are in which characters an implementation can represent, how errors are signalled, and the time complexity of doing the lookup.

This procedure can raise exceptions with the following condition types:
&assertion (R6RS)
The wrong number of arguments was passed or an argument was outside its domain. Raised if k is not a valid index of string.
R7RS
The assertions described above are errors. Implementations may signal an error, extend the procedure's domain of definition to include such arguments, or fail catastrophically.

string-set!(3scm), vector-ref(3scm), open-string-input-port(3scm)

R4RS, IEEE Scheme, R5RS, R6RS, R7RS

First introduced in R2RS. Scheme before R2RS running on MacLISP had a similar getchar function, but it used one-origin indexing and worked on atomic symbols instead of character strings.

This page is part of the scheme-manpages project. It includes materials from the RnRS documents. More information can be found at https://weinholt.se/scheme/manpages/.

It is easy to get the index validity check wrong. GNU Guile 3.0.8 segfaults on evaluating (string-ref "" -1).
2022-04-04