Skip to main content

Strings

Construction​

A string can be written inline between a single pair of double quotes or via a multi-line block between three pairs of double-quotes.

Inline​

An example of an inline string is "abc". A double quote can appear in an inline string by escaping it with \ as in "ab\"cd". Here is a list of some characters that can be expressed via escaping:

  • " via \",
  • a tab via \t,
  • a new line via \n, and
  • \ via \\.

Block​

Here is an example of a block string, which is defined using three pairs of double quotes.

myMultiLineString =
"""
This is the first line of my "string"
and this is the last line.
""";

where the text is interprated literally. In particular, all white space is included and all escape sequences are ignored.

Operations​

The following operations are available on strings.

  • length(x): the number of characters in a string. For example, length("abc") is 3.
  • x + y: the result of concatenating x and y. For example, "abc" + "def" evaluates to "abcdef".
  • matches(string, pattern): returns true if and only if pattern occurs in string, case-sensitive. For example, matches("def", "def") and matches("abcdefefg", "*def*") both return true.
  • substring(s, b, e): the substring of string s starting from index b (inclusive) and ending at index e ( exclusive). For example,substring("abcdef", 0, 6) is "abcdef", substring("abcdef", 1, 3) is "bc" (empty string), and substring("abcdef", 1, 1) is "".
  • prefix(s, n): the first n characters of string s. For example, prefix("abcdef", 3) is "abc" , prefix("abcdef", 0) is "" (empty string), and prefix("abcdef", 10) is "abcdef".
  • suffix(s, n): the last n characters of string s. For example, suffix("abcdef", 3) is "def" , suffix("abcdef", 0) is "" (empty string), and suffix("abcdef", 10) is "abcdef".
  • toUpperCase(x) and toLowerCase(x): respectively change all alphabetic characters in the string to upper- and lower-case. For example, toUpperCase("UpperCase") is "UPPERCASE" andtoLowerCase("LowerCase") is "lowercase".
  • trim(x): removes all leading and trailing whitespace (space, tab, newline, form feed, and carriage return) from string x. For example, trim(" hello ") is "hello" and trim(" ") is "" (empty string).
  • replace(text, target, replacement): replaces every occurrence of target in text with replacement. All three arguments must be strings. For example, replace("abc-def", "-", "_") is "abc_def", replace("abc-def", "-", "") is "abcdef" and replace("abab", "a", "cd") is "cdbcdb".