String Functions in Chapel

Chapel provides several useful string-related functions. Here are some examples to give you a sense of the language’s string manipulation capabilities.

use IO;

// We define a shorthand for writeln as we'll use it a lot below.
proc p(args...) {
  writeln(args);
}

proc main() {
  // Here's a sample of the string functions available in Chapel.
  // Note that in Chapel, many of these are methods on the string
  // itself, rather than standalone functions.

  p("Contains:  ", "test".contains("es"));
  p("Count:     ", "test".count("t"));
  p("StartsWith:", "test".startsWith("te"));
  p("EndsWith:  ", "test".endsWith("st"));
  p("IndexOf:   ", "test".indexOf("e"));
  p("Join:      ", " ".join(["a", "b"]));
  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());
}

To run the program, save it as string_functions.chpl and use the Chapel compiler:

$ chpl string_functions.chpl -o string_functions
$ ./string_functions
Contains:   true
Count:      2
StartsWith: true
EndsWith:   true
IndexOf:    1
Join:       a b
Repeat:     aaaaa
Replace:    f00
Replace:    f0o
Split:      a b c d e
ToLower:    test
ToUpper:    TEST

Chapel provides a rich set of string manipulation methods. Unlike some languages where string functions are part of a separate library, in Chapel many of these operations are methods on the string type itself. This makes the syntax more object-oriented and often more intuitive to use.

Note that Chapel’s string methods are similar to those in other modern programming languages, making it relatively easy for developers familiar with other languages to work with strings in Chapel.