String Functions in Scheme

Scheme provides several built-in procedures for string manipulation. Here are some examples to give you a sense of the available functionality.

(define (p . args)
  (for-each display args)
  (newline))

(p "Contains:  " (string-contains "test" "es"))
(p "Count:     " (count (lambda (c) (char=? c #\t)) "test"))
(p "HasPrefix: " (string-prefix? "te" "test"))
(p "HasSuffix: " (string-suffix? "st" "test"))
(p "Index:     " (string-index "test" #\e))
(p "Join:      " (string-join '("a" "b") "-"))
(p "Repeat:    " (make-string 5 #\a))
(p "Replace:   " (string-replace "foo" "o" "0"))
(p "Replace:   " (string-replace-first "foo" "o" "0"))
(p "Split:     " (string-split "a-b-c-d-e" #\-))
(p "ToLower:   " (string-downcase "TEST"))
(p "ToUpper:   " (string-upcase "test"))

Here’s a sample of the functions available for string manipulation in Scheme. Note that Scheme’s approach to string operations is somewhat different from other languages:

  1. string-contains checks if one string contains another.
  2. count with a predicate function is used to count occurrences of a character.
  3. string-prefix? and string-suffix? check for prefixes and suffixes.
  4. string-index finds the index of a character in a string.
  5. string-join concatenates a list of strings with a separator.
  6. make-string creates a string by repeating a character.
  7. string-replace and string-replace-first for replacing substrings.
  8. string-split divides a string into a list of substrings.
  9. string-downcase and string-upcase for case conversion.

When you run this program, you should see output similar to the following:

Contains:  #t
Count:     2
HasPrefix: #t
HasSuffix: #t
Index:     1
Join:      a-b
Repeat:    aaaaa
Replace:   f00
Replace:   f0o
Split:     (a b c d e)
ToLower:   test
ToUpper:   TEST

Note that in Scheme, boolean values are represented as #t for true and #f for false. The Split result is a list of strings, represented in parentheses.