String Functions in Racket

#lang racket

(require racket/string)

; We define a shorthand for displayln as we'll use it a lot below.
(define p displayln)

; Here's a sample of the functions available in the
; string module. Since these are functions from the
; module, not methods on the string object itself,
; we need to pass the string in question as an argument
; to the function. You can find more functions in the
; Racket documentation for the string module.

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

This Racket code demonstrates various string operations similar to those in the original Go example. Here’s a brief explanation of the changes:

  1. We use #lang racket to specify the Racket language.
  2. We import the racket/string module which provides many string functions.
  3. Instead of fmt.Println, we define a shorthand p for displayln.
  4. Racket’s string functions are slightly different from Go’s:
    • string-contains? replaces Contains
    • string-count replaces Count
    • string-prefix? and string-suffix? replace HasPrefix and HasSuffix
    • string-index-of replaces Index
    • string-join replaces Join
    • make-string replaces Repeat
    • string-replace replaces Replace
    • string-split replaces Split
    • string-downcase and string-upcase replace ToLower and ToUpper
  5. We use string-append to concatenate strings for output.
  6. Some functions return booleans, so we use number->string to convert them to strings for display.

When you run this Racket program, it will produce output similar to the Go version, demonstrating various string operations in Racket.