String Functions in Nim

The standard library’s strutils module provides many useful string-related functions. Here are some examples to give you a sense of the module.

import strutils

# We alias echo to a shorter name as we'll use it a lot below.
let p = echo

proc main() =
  # Here's a sample of the functions available in strutils.
  # 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 strutils module documentation.
  
  p "Contains:  ", "test".contains("es")
  p "Count:     ", "test".count('t')
  p "StartsWith:", "test".startsWith("te")
  p "EndsWith:  ", "test".endsWith("st")
  p "Find:      ", "test".find('e')
  p "Join:      ", @["a", "b"].join("-")
  p "Repeat:    ", "a".repeat(5)
  p "Replace:   ", "foo".replace("o", "0")
  p "Replace:   ", "foo".replace("o", "0", 1)
  p "Split:     ", "a-b-c-d-e".split("-")
  p "ToLower:   ", "TEST".toLower()
  p "ToUpper:   ", "test".toUpper()

main()

When you run this program, you’ll see the following output:

$ nim c -r string_functions.nim
Contains:   true
Count:      2
StartsWith: true
EndsWith:   true
Find:       1
Join:       a-b
Repeat:     aaaaa
Replace:    f00
Replace:    f0o
Split:      @["a", "b", "c", "d", "e"]
ToLower:    test
ToUpper:    TEST

In this Nim version, we’ve used equivalent functions from the strutils module. Some notable differences:

  1. Nim uses contains instead of Contains, following its naming convention.
  2. HasPrefix and HasSuffix are replaced with startsWith and endsWith.
  3. Index is replaced with find.
  4. The Replace function in Nim replaces all occurrences by default. To replace only one occurrence, we specify the count as the last argument.
  5. Nim’s split function returns a sequence (seq) instead of a slice.

These functions demonstrate Nim’s powerful string manipulation capabilities, which are similar to those found in other modern programming languages.