String Functions in Wolfram Language

The standard library’s StringCases, StringCount, and other built-in functions provide many useful string-related operations. Here are some examples to give you a sense of these functions.

(* We define a print function for convenience *)
p[args___] := Print[StringJoin[args]]

(* Here's a sample of the string functions available in Wolfram Language *)
p["Contains:  ", ToString@StringContainsQ["test", "es"]]
p["Count:     ", ToString@StringCount["test", "t"]]
p["HasPrefix: ", ToString@StringStartsQ["test", "te"]]
p["HasSuffix: ", ToString@StringEndsQ["test", "st"]]
p["Index:     ", ToString@StringPosition["test", "e"][[1, 1]]]
p["Join:      ", StringJoin["-", {"a", "b"}]]
p["Repeat:    ", StringRepeat["a", 5]]
p["Replace:   ", StringReplace["foo" -> {"o" -> "0"}]]
p["Replace:   ", StringReplace["foo" -> {"o" -> "0"}, 1]]
p["Split:     ", ToString@StringSplit["a-b-c-d-e", "-"]]
p["ToLower:   ", ToLowerCase["TEST"]]
p["ToUpper:   ", ToUpperCase["test"]]

When you run this code, you’ll see output similar to:

Contains:  True
Count:     2
HasPrefix: True
HasSuffix: True
Index:     2
Join:      a-b
Repeat:    aaaaa
Replace:   f00
Replace:   f0o
Split:     {a, b, c, d, e}
ToLower:   test
ToUpper:   TEST

In Wolfram Language, string manipulation functions are typically built-in and don’t require importing a separate package. The syntax is generally more functional, with the string being the first argument to most functions.

Note that some functions have slightly different names or behavior:

  • StringContainsQ is used instead of Contains
  • StringStartsQ and StringEndsQ replace HasPrefix and HasSuffix
  • StringPosition returns a list of positions, so we take the first element for Index
  • StringJoin works differently, so we adjusted the example
  • StringReplace can use rules for replacement
  • ToLowerCase and ToUpperCase are used instead of ToLower and ToUpper

These functions provide powerful string manipulation capabilities in Wolfram Language.