[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.18.4 String ports

String ports are the ports that you can read from or write to memory.

Function: open-input-string string
[SRFI-6] Creates an input string port that has the content string. This is a more efficient way to access a string in order rather than using string-ref with incremental index.

 
(define p (open-input-string "foo x"))
(read p) => foo
(read-char p) => #\space
(read-char p) => #\x
(read-char p) => #<eof>
(read-char p) => #<eof>

Function: open-output-string
[SRFI-6] Creates an output string port. Anything written to the port is accumulated in the buffer, and can be obtained as a string by get-output-string. This is a far more efficient way to construct a string sequentially than pre-allocate a string and fill it with string-set!.

Function: get-output-string port
[SRFI-6] Takes an output string port port and returns a string that has been accumulated to port so far. If a byte data has been written to the port, this function re-scans the buffer to see if it can consist a complete string; if not, an incomplete string is returned.

Function: call-with-input-string string proc
Function: call-with-output-string proc
Function: with-input-from-string string thunk
Function: with-output-to-string thunk
These utility functions are trivially defined as follows. The interface is parallel to the file port version.
 
(define (call-with-output-string proc)
  (let ((out (open-output-string)))
    (proc out)
    (get-output-string out)))

(define (call-with-input-string str proc)
  (let ((in (open-input-string str)))
    (proc in)))

(define (with-output-to-string thunk)
  (let ((out (open-output-string)))
    (with-output-to-port out thunk)
    (get-output-string out)))

(define (with-input-from-string str thunk)
  (with-input-from-port (open-input-string str) thunk))

Function: call-with-string-io str proc
Function: with-string-io str thunk
 
(define (call-with-string-io str proc)
  (let ((out (open-output-string))
        (in  (open-input-string str)))
    (proc in out)
    (get-output-string out)))

(define (with-string-io str thunk)
  (with-output-to-string
    (lambda ()
      (with-input-from-string str
        thunk))))

Function: write-to-string obj &optional writer
Function: read-from-string string &optional start end
These convenience functions cover commin idioms using string ports.
 
(write-to-string obj writer)
  ==
  (with-output-to-string (lambda () (writer obj)))

(read-from-string string)
  ==
  (with-input-from-string string read)
The default value of writer is the procedure write. The default values of start and end is 0 and the length of string.

Portability note: Common Lisp has these functions, with different optional arguments. STk has read-from-string without optional argument.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

This document was generated by Ken Dickey on November, 28 2002 using texi2html