ZetCode

Scheme string processing

last modified November 25, 2026 Guile 3.0

String processing means taking text apart, cleaning it, and putting it together again: trimming spaces, splitting lines into words, counting, changing case, padding, replacing, and parsing. This article combines the string procedures of GNU Guile 3.0.7, most of which come from SRFI 13, into small text tools. The strings article introduces the basic operations, the characters article covers character sets, and the regular expressions article covers pattern-based searching.

Trimming

Text read from users or files often has extra spaces at the ends. string-trim removes whitespace from the start of a string, string-trim-right from the end, and string-trim-both from both ends.

trimming.scm
(define line "   Hello there!   ")

(write (string-trim line))
(newline)
(write (string-trim-right line))
(newline)
(write (string-trim-both line))
(newline)

(write (string-trim-both "***Sale***" #\*))
(newline)
(write (string-trim-both "...Wait, what?!" char-set:punctuation))
(newline)
(write (string-trim-right "total: 42   \t\n"))
(newline)

write shows the quotes, so the remaining spaces are visible. An optional second argument says what to remove instead of whitespace: a character such as #\* or a character set such as char-set:punctuation. Only the ends are trimmed, so the comma inside "Wait, what" stays. Whitespace includes tabs and newlines, which string-trim-right removes after the number.

$ guile trimming.scm
"Hello there!   "
"   Hello there!"
"Hello there!"
"Sale"
"Wait, what"
"total: 42"

Splitting into words

string-split cuts a string at every delimiter, so two delimiters in a row give an empty string. string-tokenize works the other way round: it returns the runs of characters that belong to a character set, so the delimiters never appear in the result, however many there are.

words.scm
(define text "One fish,  two fish; red fish -- blue fish.")

(write (string-split text #\space))
(newline)
(write (string-tokenize text))
(newline)
(write (string-tokenize text char-set:letter))
(newline)

(define separators (char-set #\, #\;))

(write (string-split "a,b;;c" separators))
(newline)
(write (string-tokenize "a,b;;c" (char-set-complement separators)))
(newline)

(define (normalize-spaces s)
  (string-join (string-tokenize s) " "))

(write (normalize-spaces "  too   many\tspaces \n here  "))
(newline)

Without a character set, string-tokenize uses char-set:graphic, the visible characters, so the words keep their punctuation. With char-set:letter, only the letters form words. In Guile, string-split also accepts a character set of delimiters, but it still keeps the empty field between two semicolons. To split on several delimiters and drop the empty fields, the program tokenizes with the complement of the delimiter set: every character except a comma or a semicolon. normalize-spaces joins the tokens with single spaces, which removes all leading, trailing, and repeated whitespace at once.

$ guile words.scm
("One" "fish," "" "two" "fish;" "red" "fish" "--" "blue" "fish.")
("One" "fish," "two" "fish;" "red" "fish" "--" "blue" "fish.")
("One" "fish" "two" "fish" "red" "fish" "blue" "fish")
("a" "b" "" "c")
("a" "b" "c")
"too many spaces here"

Counting words, lines, and letters

With words as a list, the list procedures can compute statistics about a text. This example is a small version of the Unix wc command that also finds the longest word and the average word length.

stats.scm
(define text "The quick brown fox
jumps over the lazy dog.
It barked twice.")

(define (words s)
  (string-tokenize s char-set:letter))

(define (longest-word ws)
  (let loop ((ws ws) (best ""))
    (cond ((null? ws) best)
          ((> (string-length (car ws)) (string-length best))
           (loop (cdr ws) (car ws)))
          (else (loop (cdr ws) best)))))

(define ws (words text))

(display "characters: ")
(display (string-length text))
(newline)
(display "letters: ")
(display (string-count text char-alphabetic?))
(newline)
(display "lines: ")
(display (length (string-split text #\newline)))
(newline)
(display "words: ")
(display (length ws))
(newline)
(display "longest: ")
(display (longest-word ws))
(newline)
(display "average length: ")
(display (exact->inexact (/ (apply + (map string-length ws)) (length ws))))
(newline)

The text spans three lines; the newlines are part of the string literal. string-length counts all characters, including spaces, dots, and newlines, while string-count with char-alphabetic? counts only the letters. Splitting at newlines gives the lines. words takes only letters, so the dot after dog does not make that word longer. longest-word keeps the first of several words with the same length because it replaces the best word only when a longer one appears.

$ guile stats.scm
characters: 61
letters: 48
lines: 3
words: 12
longest: barked
average length: 4.0

Capitalising words

string-titlecase converts the first letter of every word to upper case and the rest to lower case. Its idea of a word is a run of letters, which gives surprising results with apostrophes. Writing the procedure by hand gives control over what a word is.

capitals.scm
(write (string-titlecase "it's o'neil from new-york"))
(newline)

(define (capitalize word)
  (if (string-null? word)
      word
      (string-append (string-upcase (substring word 0 1))
                     (string-downcase (substring word 1)))))

(define (capitalize-words s)
  (string-join (map capitalize (string-split s #\space)) " "))

(write (capitalize-words "it's o'neil from new-york"))
(newline)

(define (snake->camel s)
  (let ((parts (string-split s #\_)))
    (apply string-append (car parts) (map capitalize (cdr parts)))))

(define (camel->snake s)
  (string-downcase
   (list->string
    (let loop ((cs (string->list s)) (acc '()))
      (cond ((null? cs) (reverse acc))
            ((char-upper-case? (car cs))
             (loop (cdr cs) (cons (car cs) (cons #\_ acc))))
            (else (loop (cdr cs) (cons (car cs) acc))))))))

(write (snake->camel "user_first_name"))
(newline)
(write (camel->snake "userFirstName"))
(newline)

string-titlecase starts a new word after the apostrophe, so it's becomes It'S. capitalize changes only the first character of a whole word, and capitalize-words applies it to the words between spaces; this fixes It's, but treats O'neil and New-york as single words. No simple rule handles every name. The same idea converts identifiers between styles. snake->camel splits at underscores and capitalises every part after the first, and camel->snake walks over the characters and puts an underscore before each capital letter.

$ guile capitals.scm
"It'S O'Neil From New-York"
"It's O'neil From New-york"
"userFirstName"
"user_first_name"

Palindromes

A palindrome reads the same backwards and forwards. For sentences, spaces, punctuation, and case are ignored, so the text is normalized before it is compared with its reverse.

palindromes.scm
(define (normalize s)
  (string-downcase (string-filter char-alphabetic? s)))

(define (palindrome? s)
  (let ((t (normalize s)))
    (string=? t (string-reverse t))))

(for-each (lambda (s)
            (write s)
            (display (if (palindrome? s) " yes" " no"))
            (newline))
          '("radar"
            "Scheme"
            "A man, a plan, a canal: Panama!"
            "Was it a car or a cat I saw?"
            "Jelenovi pivo nelej"
            "Never odd or even"
            "Step on no pets, please"))

normalize keeps only the letters with string-filter and converts them to lower case. palindrome? compares the result with string-reverse of it. "Jelenovi pivo nelej" is a well-known Slovak palindrome. The last sentence fails because of the word please.

$ guile palindromes.scm
"radar" yes
"Scheme" no
"A man, a plan, a canal: Panama!" yes
"Was it a car or a cat I saw?" yes
"Jelenovi pivo nelej" yes
"Never odd or even" yes
"Step on no pets, please" no

Padding and truncating

Text in columns needs strings of a fixed width. string-pad adds spaces on the left and string-pad-right on the right. Both also shorten a string that is too long, and an optional character replaces the space.

padding.scm
(write (string-pad "42" 6))
(newline)
(write (string-pad-right "42" 6))
(newline)
(write (string-pad "7" 3 #\0))
(newline)
(write (string-pad "Bratislava" 5))
(newline)
(write (string-pad-right "Bratislava" 5))
(newline)

(define (truncate-text s width)
  (if (<= (string-length s) width)
      s
      (string-append (substring s 0 (- width 1)) "…")))

(define (center s width)
  (let* ((total (max 0 (- width (string-length s))))
         (left (quotient total 2)))
    (string-append (make-string left #\space)
                   s
                   (make-string (- total left) #\space))))

(define cities '("Bratislava" "Kosice" "Banska Bystrica" "Nitra"))

(for-each (lambda (city)
            (display "|")
            (display (string-pad-right (truncate-text city 10) 10))
            (display "|")
            (display (center city 17))
            (display "|")
            (newline))
          cities)

string-pad right-aligns the text, which suits numbers, and pads 7 with zeros to 007. A string longer than the width is cut, and string-pad keeps its end: "Bratislava" becomes "slava". string-pad-right keeps the beginning. To show that text was cut, truncate-text replaces the last character that fits with an ellipsis. center puts half of the free space on each side, and the odd space on the right. The ellipsis is a single Unicode character, so it counts as one in the width. Aligning numbers with decimal places is the job of format, covered in the number formatting article.

$ guile padding.scm
"    42"
"42    "
"007"
"slava"
"Brati"
|Bratislava|   Bratislava    |
|Kosice    |     Kosice      |
|Banska By…| Banska Bystrica |
|Nitra     |      Nitra      |

Replacing substrings

Guile's string library has no procedure that replaces every occurrence of a substring, but one is easy to build on string-contains, which accepts a start index. SRFI 13's string-replace replaces a range of indexes instead.

replacing.scm
(define (replace-all s old new)
  (let ((n (string-length old)))
    (let loop ((start 0) (parts '()))
      (let ((pos (string-contains s old start)))
        (if pos
            (loop (+ pos n)
                  (cons* new (substring s start pos) parts))
            (string-concatenate
             (reverse (cons (substring s start) parts))))))))

(write (replace-all "one fish, two fish" "fish" "cat"))
(newline)
(write (replace-all "aaaa" "aa" "b"))
(newline)
(write (replace-all "no match here" "xyz" "!"))
(newline)

(write (string-replace "Hello there" "Bye" 0 5))
(newline)

(define (expand-template template values)
  (let loop ((s template) (values values))
    (if (null? values)
        s
        (loop (replace-all s
                           (string-append "{" (symbol->string (caar values)) "}")
                           (cdar values))
              (cdr values)))))

(display (expand-template "Dear {name}, your order {id} has shipped. Thanks, {name}!"
                          '((name . "Lucia") (id . "A-1042"))))
(newline)

replace-all searches from start, collects the text before each match and the replacement in reverse order, and continues after the match. cons* adds two elements at once. When no match remains, the rest of the string is added, the list is reversed, and string-concatenate joins it. Because the search continues after the match, the matches do not overlap, and "aaaa" gives "bb". string-replace replaces the characters from index 0 up to 5 with "Bye". expand-template fills {name} placeholders from an association list by calling replace-all once for each key.

$ guile replacing.scm
"one cat, two cat"
"bb"
"no match here"
"Bye there"
Dear Lucia, your order A-1042 has shipped. Thanks, Lucia!

Parsing CSV lines

In a CSV file, a field that contains a comma is put in double quotes, and a quote inside such a field is written twice. Splitting at commas breaks these fields, so a parser has to read the line character by character and remember whether it is inside quotes.

csv.scm
(define (parse-csv-line line)
  (let loop ((i 0) (field '()) (fields '()) (quoted? #f))
    (define (finish)
      (cons (list->string (reverse field)) fields))
    (if (= i (string-length line))
        (reverse (finish))
        (let ((c (string-ref line i)))
          (cond (quoted?
                 (cond ((not (char=? c #\"))
                        (loop (+ i 1) (cons c field) fields #t))
                       ((and (< (+ i 1) (string-length line))
                             (char=? (string-ref line (+ i 1)) #\"))
                        (loop (+ i 2) (cons #\" field) fields #t))
                       (else (loop (+ i 1) field fields #f))))
                ((char=? c #\") (loop (+ i 1) field fields #t))
                ((char=? c #\,) (loop (+ i 1) '() (finish) #f))
                (else (loop (+ i 1) (cons c field) fields #f)))))))

(define lines
  '("Lucia,34,Bratislava"
    "\"Novak, Peter\",41,Kosice"
    "\"The \"\"Blue\"\" Cafe\",,Nitra"
    "a,,"))

(for-each (lambda (line)
            (display line)
            (newline)
            (display "  -> ")
            (write (parse-csv-line line))
            (newline))
          lines)

The loop carries the index, the characters of the current field in reverse order, the finished fields, and a flag for quoted text. The internal procedure finish turns the current field into a string and adds it to the list. Outside quotes, a comma finishes a field and a quote starts quoted text. Inside quotes, a comma is an ordinary character, two quotes in a row stand for one quote, and a single quote ends the quoted text. At the end of the line, the last field is finished, so a line that ends with a comma has an empty last field.

$ guile csv.scm
Lucia,34,Bratislava
  -> ("Lucia" "34" "Bratislava")
"Novak, Peter",41,Kosice
  -> ("Novak, Peter" "41" "Kosice")
"The ""Blue"" Cafe",,Nitra
  -> ("The \"Blue\" Cafe" "" "Nitra")
a,,
  -> ("a" "" "")

Wrapping text

Wrapping breaks a paragraph into lines no longer than a given width. The greedy method puts as many words on a line as fit and starts a new line with the first word that does not.

wrap.scm
(define (wrap text width)
  (let loop ((words (string-tokenize text)) (line "") (lines '()))
    (cond ((null? words)
           (reverse (if (string-null? line) lines (cons line lines))))
          ((string-null? line)
           (loop (cdr words) (car words) lines))
          ((<= (+ (string-length line) 1 (string-length (car words))) width)
           (loop (cdr words) (string-append line " " (car words)) lines))
          (else
           (loop words "" (cons line lines))))))

(define text "Scheme is a small, dynamically typed language from the Lisp
family. Programs are written as nested lists in parentheses, and procedures
are first-class values.")

(define (show-wrapped width)
  (display (make-string width #\-))
  (newline)
  (for-each (lambda (line) (display line) (newline))
            (wrap text width)))

(show-wrapped 40)
(show-wrapped 25)

wrap tokenizes the text, so the original line breaks and repeated spaces disappear. The loop keeps the current line and the finished lines. A word joins the line when the line length, one space, and the word length together fit the width. Otherwise the line is finished and the same word is tried again on an empty line. A word longer than the width would still get a line of its own. show-wrapped prints a ruler of the width followed by the lines.

$ guile wrap.scm
----------------------------------------
Scheme is a small, dynamically typed
language from the Lisp family. Programs
are written as nested lists in
parentheses, and procedures are
first-class values.
-------------------------
Scheme is a small,
dynamically typed
language from the Lisp
family. Programs are
written as nested lists
in parentheses, and
procedures are
first-class values.

Source

Strings — GNU Guile Reference Manual

SRFI 13: String Libraries

In this article we have trimmed strings, split text into words with string-tokenize and character sets, computed text statistics, capitalised words and converted identifiers, recognised palindromes, padded and truncated text, replaced substrings, parsed CSV lines with quoted fields, and wrapped a paragraph. The strings article covers the basic operations, and the regular expressions article replaces text by patterns.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Scheme tutorials.